PHP code example of zero-to-prod / data-model-factory
1. Go to this page and download the library: Download zero-to-prod/data-model-factory library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
zero-to-prod / data-model-factory example snippets
class User
{
use \Zerotoprod\DataModelFactory\DataModel;
public $first_name;
public $last_name;
public $address;
public static function factory(array $states = []): UserFactory
{
return new UserFactory($states);
}
}
class UserFactory
{
use \Zerotoprod\DataModelFactory\Factory;
/* This is the class to be instantiated with the make() method */
protected $model = User::class;
protected function definition(): array
{
return [
'first_name' => 'John',
'last_name' => 'N/A',
'address' => [
'street' => 'Memory Lane'
]
];
}
public function setStreet(string $value): self
{
/** Dot Syntax */
return $this->state('address.street', $value);
}
public function setFirstName(string $value): self
{
/** Array Syntax */
return $this->state(['first_name' => $value]);
}
public function setLastName(): self
{
/** Closure Syntax */
return $this->state(function ($context) {
return ['first_name' => $context['last_name']];
});
}
/* Optionally implement for better static analysis */
public function make(): User
{
return $this->instantiate();
}
}
$User = UserFactory::factory([User::last_name => 'Doe'])
->setFirstName('Jane')
->make();
User::factory([User::last_name => 'Doe'])->make(); // Also works for this example
echo $User->first_name; // 'Jane'
echo $User->last_name; // 'Doe'