Having discussed different aspects of https://matthiasnoback.nl/2022/08/what-is-a-simple-solution/, let's start with the first topic that should be scrutinized regarding their simplicity: persisting model objects. It's when you instantiate a model object and then call save() on it: $user = new User('Matthias'); $user->save(); In terms of simplicity as seen from the client's perspective, this is amazing.

If we'd create our own AR implementation, then the save() function looks something like this: final class User { public function __construct( private string $name ) { } public function save(): void { // get the DB connection $connection->execute([ $this->name ]); }}

This parent class defines a few abstract methods so the model is forced to fill in the details: abstract class Model { public static Connection $connection; abstract protected function tableName(): string; /** * @return array */ abstract protected function dataToSave(): array; public function save(): void { $dataToSave = $this->dataToSave(); $columnsAndValues = /* turn into column = ? */; $values = /* values for parameter binding */; $this->connection->execute( 'INSERT INTO '. $this->tableName() . ' SET '. $columnsAndValues, $values ); }}

We'll add one method to User: final class User { public function __construct( private string $name ) { } /** * @return array */ public function asDatabaseRecord(): array { return [ 'name' => $this->name ]; }}
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners