Laravel Brussel - 2018-03-06
Grummfy
Jonathan Van Belle
@Grummfy
@Grummfy@mamot.fr
me@grummfy.be
github.com/grummfy
Open source contributor: atoum, hoa ...
Rust meetup organizer
VS
Simpler database structure
NoSql...
MySql > 5.7 | MariaDb > 10.2 | Postgresql > 9.2? | |
---|---|---|---|
json column | ✔ | ✘ | ✔ |
jsonb column | ✘ | ✘ | ✔ |
search | ✔ | ✔ | ✔ |
virtual col | ✔ | ✔ | ✔ |
short syntax | ✔ | ✔ | ✔ |
<?php
class Shop extends Eloquent {
protected $fillable = ['address'];
public function getAddressAttribute(string $value): Address {
$data = json_decode($value);
return new Address(
$data->street, $data->number,
$data->city, $data->zipCode,
$data->country);
}
public function setAddressAttribute(Address $address) {
$this->attributes['address'] = json_encode($address);
}
}
<?php
class Shop extends Eloquent {
protected $cast = ['address' => 'json'];
protected $fillable = ['address'];
public function getAddressAttribute(array $value): Address {
return new Address(
$data['street'], $data['number'],
$data['city'], $data['zipCode'],
$data['country']);
}
public function setAddressAttribute(Address $address): string {
$this->attributes['address'] = json_encode($address);
}
}
<?php
class Shop extends Eloquent {
use CastableModel;
protected $cast = ['address' => 'myAddress'];
protected $fillable = ['address'];
public function toMyAddress(Address $address): string {
return json_encode($address);
}
public function fromMyAddress(string $address): Address {
return Address::fromStdClass($this->fromJson($address, true));
}
}
<?php
class Contact extends Eloquent {
use CastableModel, JsonReadOnlyCollectionCastable;
protected $cast = ['phones' => 'jsonReadOnlyCollection'];
protected $fillable = ['phones'];
protected $castParameters = ['phones' => Phone::class];
}
Collection is not so simple...
<?php
public function addPhone(string $prefix, string $number): self {
if (is_null($this->phones)) {
$this->phones = new ReadOnlyCollection();
}
$this->phones = $this->phones->push(new Phone($prefix, $number));
return $this;
}
{"street": "test street", "number": 5, "city": "Brussels"}
[{"prefix":32, "number":"123456789"}{"prefix":33,"number":"6123456789"}]
$table->string('street1')->virtualAs('address->>\'$.street\'');
$table->string('street2')->storedAs('address->>\'$.street\'');