### Configure Default Sequence Start Number Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Use `Fabricate::config` to set a global default starting number for all sequences. This can be overridden for individual sequences. ```php Fabricate::config(function($config) { $config->sequence_start = 100; }); ``` -------------------------------- ### Run Fabricate Testcases Locally Source: https://github.com/sizuhiko/fabricate/blob/develop/CONTRIBUTING.markdown Execute all Fabricate test cases locally using this command. Ensure you have PHPUnit 3.5 or higher installed. ```bash ./lib/Cake/Console/cake test Fabricate AllFabricate ``` -------------------------------- ### Configure Fabricate with Custom Settings Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Customize Fabricate's behavior by setting options like sequence start, adaptor, and Faker locale. This configuration should be placed in a bootstrap file. ```php Fabricate::config(function($config) { $config->sequence_start = 1; $config->adaptor = new Fabricate\Adaptor\CakePHPAdaptor(); $config->faker = \Faker\Factory::create('ja_JP'); }); ``` -------------------------------- ### Configure Fabricate Instance Source: https://context7.com/sizuhiko/fabricate/llms.txt Sets global options for the Fabricate instance, including the ORM adaptor, sequence start number, Faker locale, and text field size limit. This must be called before any generation method. ```php use Fabricate\Fabricate; use Fabricate\Adaptor\FabricateArrayAdaptor; use Fabricate\Model\FabricateModel; // Define a schema using the built-in array adaptor (framework-agnostic) $adaptor = new FabricateArrayAdaptor(); $adaptor::$definitions = [ 'Post' => (new FabricateModel('Post')) ->addColumn('id', 'integer') ->addColumn('author_id', 'integer', ['null' => false]) ->addColumn('title', 'string', ['null' => false, 'limit' => 50]) ->addColumn('body', 'text') ->addColumn('published', 'string', ['limit' => 1]) ->addColumn('created', 'datetime') ->addColumn('updated', 'datetime') ->belongsTo('Author', 'author_id', 'User') ->hasMany('PostTag', 'post_id'), 'User' => (new FabricateModel('User')) ->addColumn('id', 'integer') ->addColumn('user', 'string', ['null' => true, 'limit' => 255]) ->addColumn('password', 'string', ['null' => true, 'limit' => 255]) ->addColumn('created', 'datetime') ->addColumn('updated', 'datetime') ->hasMany('Post', 'author_id'), ]; Fabricate::config(function ($config) use ($adaptor) { $config->adaptor = $adaptor; // required: ORM adaptor $config->sequence_start = 1; // default auto-increment start $config->faker = \Faker\Factory::create('en_US'); // Faker locale $config->text_size_limit = 200; // max chars for 'text' columns }); ``` -------------------------------- ### Generate Auto-Incrementing Sequences with `$world->sequence()` Source: https://context7.com/sizuhiko/fabricate/llms.txt Use `$world->sequence()` to generate auto-incrementing integers within callbacks. You can specify a name for the sequence, an optional start value, and an optional transformer callback. The global `sequence_start` configuration value is used as the default if no start value is provided. ```php use Fabricate\Fabricate; // Configure a custom global sequence start Fabricate::config(function ($config) { $config->sequence_start = 100; }); $results = Fabricate::attributes_for('Post', 5, function ($data, $world) { return [ // Uses global sequence_start (100) as starting value 'id' => $world->sequence('id'), // Custom start value (1) with string transformer callback 'title' => $world->sequence('title', 1, function ($i) { return "Post Title {$i}"; }), // Sequence-based unique email 'email' => $world->sequence('email', function ($i) { return "user{$i}@example.com"; }), ]; }); // $results[0]: ['id' => 100, 'title' => 'Post Title 1', 'email' => 'user100@example.com'] // $results[1]: ['id' => 101, 'title' => 'Post Title 2', 'email' => 'user101@example.com'] // $results[4]: ['id' => 104, 'title' => 'Post Title 5', 'email' => 'user104@example.com'] ``` -------------------------------- ### Configure Fabricate with CakePHP Adaptor Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Configure Fabricate to use a specific adaptor, such as CakeFabricateAdaptor for CakePHP. This setup is typically done in a bootstrap file. ```php use Fabricate\Fabricate; use CakeFabricate\Adaptor\CakeFabricateAdaptor; Fabricate::config(function($config) { $config->adaptor = new CakeFabricateAdaptor(); }); ``` -------------------------------- ### Fabricate::config Source: https://context7.com/sizuhiko/fabricate/llms.txt Configures the global Fabricate instance with options like ORM adaptor, sequence start, Faker locale, and text size limit. This method must be called before any generation methods. ```APIDOC ## Fabricate::config($callback) ### Description Sets global options including the ORM adaptor, sequence start number, Faker locale, and text field size limit. Must be called before any generation method. The callback receives a `FabricateConfig` instance whose public properties can be set directly. ### Method `Fabricate::config` ### Parameters - **$callback** (callable) - A callback function that receives a `FabricateConfig` instance. ### Request Example ```php use Fabricate\Fabricate; use Fabricate\Adaptor\FabricateArrayAdaptor; use Fabricate\Model\FabricateModel; // Define a schema using the built-in array adaptor (framework-agnostic) $adaptor = new FabricateArrayAdaptor(); $adaptor::$definitions = [ 'Post' => (new FabricateModel('Post')) ->addColumn('id', 'integer') ->addColumn('author_id', 'integer', ['null' => false]) ->addColumn('title', 'string', ['null' => false, 'limit' => 50]) ->addColumn('body', 'text') ->addColumn('published', 'string', ['limit' => 1]) ->addColumn('created', 'datetime') ->addColumn('updated', 'datetime') ->belongsTo('Author', 'author_id', 'User') ->hasMany('PostTag', 'post_id'), 'User' => (new FabricateModel('User')) ->addColumn('id', 'integer') ->addColumn('user', 'string', ['null' => true, 'limit' => 255]) ->addColumn('password', 'string', ['null' => true, 'limit' => 255]) ->addColumn('created', 'datetime') ->addColumn('updated', 'datetime') ->hasMany('Post', 'author_id'), ]; Fabricate::config(function ($config) use ($adaptor) { $config->adaptor = $adaptor; // required: ORM adaptor $config->sequence_start = 1; // default auto-increment start $config->faker = \Faker\Factory::create('en_US'); // Faker locale $config->text_size_limit = 200; // max chars for 'text' columns }); ``` ``` -------------------------------- ### Reset Fabricate Singleton with `clear()` Source: https://context7.com/sizuhiko/fabricate/llms.txt Use `Fabricate::clear()` in test setup or teardown methods to ensure test isolation by resetting all registered definitions, traits, configuration, and sequence state. ```php use Fabricate\Fabricate; // In a PHPUnit test case class MyTest extends \PHPUnit\Framework\TestCase { public function setUp() { parent::setUp(); // Reset all definitions, config, and sequences before each test Fabricate::clear(); $adaptor = new \Fabricate\Adaptor\FabricateArrayAdaptor(); $adaptor::$definitions = [ 'Post' => (new \Fabricate\Model\FabricateModel('Post')) ->addColumn('id', 'integer') ->addColumn('title', 'string', ['null' => false, 'limit' => 100]) ->addColumn('body', 'text'), ]; Fabricate::config(function ($config) use ($adaptor) { $config->adaptor = $adaptor; }); } public function testPostGeneration() { $post = Fabricate::attributes_for('Post'); $this->assertNotEmpty($post[0]['title']); } } ``` -------------------------------- ### FabricateContext#sequence API Usage Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md The `FabricateContext#sequence` method generates unique values. It accepts a name, an optional starting number, and an optional callback function for custom value generation. ```php $world->sequence('id') ``` ```php $world->sequence('id', 10) ``` ```php $world->sequence('title', function($i){ return "Title {$i}"; } ``` ```php // or with start number $world->sequence('title', 1, function($i){ return "Title {$i}"; } ``` -------------------------------- ### Create a Basic Model Instance Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Generate and save a new instance of a specified model. This method uses schema information to populate the model. ```php Fabricate::create('Post') ``` -------------------------------- ### Set Up Associations with Fabricate::create Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Use `Fabricate::create` with a callback to define associations. The `$world->association()` method can be used to generate related records, optionally with custom attributes or using predefined definitions. ```php Fabricate::create('User', function($data, $world) { return [ 'user' => 'taro', 'Post' => $world->association('Post', 3), ]; }); ``` ```php // or can overwritten by array or callback block. Fabricate::create('User', function($data, $world) { return [ 'user' => 'taro', 'Post' => $world->association('Post', 3, function($data, $world) { return ['title'=>$world->sequence('Post.title',function($i){ return "Title-${i}"; })]; }), ]; }); ``` ```php // can use defined onbject. Fabricate::define(['PublishedPost', 'class'=>'Post'], ['published'=>'1']); Fabricate::create('User', function($data, $world) { return [ 'user' => 'taro', 'Post' => $world->association(['PublishedPost', 'association'=>'Post'], 3), ]; }); ``` ```php // can use association alias (Post belongs to Author of User class) Fabricate::define(['PublishedPost', 'class'=>'Post'], ['published'=>'1']); Fabricate::create('PublishedPost', 3, function($data, $world) { return [ 'Author' => $world->association(['User', 'association'=>'Author'], ['id'=>1,'user'=>'taro']), ]; }); ``` -------------------------------- ### Create Multiple Model Instances with Callback Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Generate a specified number of model instances using a callback function to define attributes. Attributes defined in the array passed to the callback will overwrite generated ones. ```php Fabricate::create('Post', 10, function($data){ return ["created" => "2013-10-09 12:40:28", "updated" => "2013-10-09 12:40:28"]; }); ``` -------------------------------- ### Build a Model Instance (Not Saved) Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Generate a model instance using ClassRegistry::init, without saving it to the database. Attributes can be overridden via a callback. ```php Fabricate::build(:model_name, :array_or_callback) ``` -------------------------------- ### Build Model Instance with Fabricate::build Source: https://context7.com/sizuhiko/fabricate/llms.txt Instantiate a model in memory without persisting to the database. Use a callback or array to override default attributes. ```php use Fabricate\Fabricate; // Build a single Post model instance with overridden fields $post = Fabricate::build('Post', function ($data, $world) { return [ 'title' => 'My Test Post', 'created' => '2024-06-01 12:00:00', 'updated' => '2024-06-01 12:00:00', ]; }); // With FabricateArrayAdaptor: // $post['Post']['id'] === 1 // $post['Post']['title'] === 'My Test Post' // $post['Post']['created'] === '2024-06-01 12:00:00' ``` ```php // Build using an array override $post = Fabricate::build('Post', ['published' => '1', 'author_id' => 42]); // $post['Post']['published'] === '1' // $post['Post']['author_id'] === 42 ``` -------------------------------- ### Create and Persist Records with Fabricate::create Source: https://context7.com/sizuhiko/fabricate/llms.txt Generate attributes and persist records using the adaptor's create method. Returns the adaptor's result, which varies based on the number of records created. ```php use Fabricate\Fabricate; // Persist 10 Post records, overriding timestamps $results = Fabricate::create('Post', 10, function ($data, $world) { return [ 'created' => '2024-03-01 08:00:00', 'updated' => '2024-03-01 08:00:00', ]; }); // $results[0]['Post']['id'] === 1 // $results[9]['Post']['id'] === 10 // $results[0]['Post']['created'] === '2024-03-01 08:00:00' ``` ```php // Create a single record (returns single entry, not array-of-one) $record = Fabricate::create('Post', 1, ['published' => '1']); // $record['Post']['published'] === '1' ``` ```php // Create without explicit count (defaults to 1) $record = Fabricate::create('Post', ['title' => 'Hello World']); ``` -------------------------------- ### Implement Custom ORM Adaptor with `AbstractFabricateAdaptor` Source: https://context7.com/sizuhiko/fabricate/llms.txt Extend `AbstractFabricateAdaptor` to integrate Fabricate with any ORM. Implement `getModel`, `create`, and `build` methods to define how Fabricate interacts with your ORM. ```php namespace MyApp\Test; use Fabricate\Adaptor\AbstractFabricateAdaptor; use Fabricate\Model\FabricateModel; class EloquentFabricateAdaptor extends AbstractFabricateAdaptor { private array $schemas; public function __construct(array $schemas) { $this->schemas = $schemas; } // Return a FabricateModel schema for the given model name public function getModel($modelName): ?FabricateModel { return $this->schemas[$modelName] ?? null; } // Persist each set of attributes using your ORM public function create($modelName, $attributes, $recordCount) { $results = array_map(fn($attr) => $modelName::create($attr), $attributes); return $recordCount === 1 ? $results[0] : $results; } // Instantiate without saving public function build($modelName, $data) { return new $modelName($data); } } // Register and use the custom adaptor $adaptor = new EloquentFabricateAdaptor([ 'User' => (new FabricateModel('User')) ->addColumn('id', 'integer') ->addColumn('name', 'string', ['limit' => 100]) ->addColumn('email', 'string', ['limit' => 255]), ]); Fabricate::config(fn($c) => $c->adaptor = $adaptor); $user = Fabricate::create('User', ['name' => 'Alice', 'email' => 'alice@example.com']); ``` -------------------------------- ### Create Model Instance with Overrides Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Generate and save a model instance, overriding specific attributes by passing an associative array of fields. ```php Fabricate::create('Post', ["created" => "2013-10-09 12:40:28", "updated" => "2013-10-09 12:40:28"]) ``` -------------------------------- ### Fabricate::create Source: https://context7.com/sizuhiko/fabricate/llms.txt Generates attributes and persists records to the database. Returns the adaptor's result. ```APIDOC ## `Fabricate::create($modelName, $count, $callbackOrArray)` — Generate and persist records Generates attributes and then calls the adaptor's `create` method to persist records. Returns the adaptor's result — for `FabricateArrayAdaptor`, a single record returns `['ModelName' => [...]]` and multiple records return an array of such entries. ### Parameters - **$modelName** (string) - The name of the model to create. - **$count** (int|array) - The number of records to create, or an array of attributes if count is omitted (defaults to 1). - **$callbackOrArray** (callable|array) - A callback function or an array of attributes to override. If $count is an array, this parameter is ignored. ### Request Example ```php use Fabricate\Fabricate; // Persist 10 Post records, overriding timestamps $results = Fabricate::create('Post', 10, function ($data, $world) { return [ 'created' => '2024-03-01 08:00:00', 'updated' => '2024-03-01 08:00:00', ]; }); // Create a single record (returns single entry, not array-of-one) $record = Fabricate::create('Post', 1, ['published' => '1']); // Create without explicit count (defaults to 1) $record = Fabricate::create('Post', ['title' => 'Hello World']); ``` ### Response Example (with FabricateArrayAdaptor) ```json [ { "Post": { "id": 1, "created": "2024-03-01 08:00:00", "updated": "2024-03-01 08:00:00" } }, // ... more records ] ``` ```json { "Post": { "published": "1" } } ``` ```json { "Post": { "title": "Hello World" } } ``` ``` -------------------------------- ### Define Attributes with Inheritance Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Use the 'parent' key in `Fabricate::define` to inherit attributes from another defined set. This allows for building complex attribute structures by composing definitions. ```php Fabricate::define(['PublishedPost', 'class'=>'Post'], ['published'=>'1']); Fabricate::define(['Author5PublishedPost', 'parent'=>'PublishedPost'], ['author_id'=>'5']); ``` ```php Fabricate::create('Author5PublishedPost'); ``` -------------------------------- ### Fabricate::build Source: https://context7.com/sizuhiko/fabricate/llms.txt Instantiates a model in memory without persisting it to the database. The return value depends on the adaptor used. ```APIDOC ## `Fabricate::build($modelName, $callbackOrArray)` — Instantiate a model without saving Creates a single model instance in memory (via the adaptor's `build` method) without persisting to the database. The return value is adaptor-dependent; with `FabricateArrayAdaptor` it returns `['ModelName' => [...attributes...]]`. ### Parameters - **$modelName** (string) - The name of the model to build. - **$callbackOrArray** (callable|array) - A callback function or an array of attributes to override. ### Request Example ```php use Fabricate\Fabricate; // Build a single Post model instance with overridden fields $post = Fabricate::build('Post', function ($data, $world) { return [ 'title' => 'My Test Post', 'created' => '2024-06-01 12:00:00', 'updated' => '2024-06-01 12:00:00', ]; }); // Build using an array override $post = Fabricate::build('Post', ['published' => '1', 'author_id' => 42]); ``` ### Response Example (with FabricateArrayAdaptor) ```json { "Post": { "id": 1, "title": "My Test Post", "created": "2024-06-01 12:00:00", "updated": "2024-06-01 12:00:00" } } ``` ```json { "Post": { "published": "1", "author_id": 42 } } ``` ``` -------------------------------- ### Create Topic Branch Source: https://github.com/sizuhiko/fabricate/blob/develop/CONTRIBUTING.markdown Use this command to create a new topic branch based on the master branch for your contributions. Avoid working directly on the master branch to prevent conflicts. ```bash git branch master/my_contribution master git checkout master/my_contribution ``` -------------------------------- ### Access Faker Instance with `$world->faker()` Source: https://context7.com/sizuhiko/fabricate/llms.txt Access the configured `Faker ame` instance within any definition or generation callback using `$world->faker()`. This allows you to generate realistic, locale-aware fake data for specific fields. You can also mix Faker with sequences to ensure uniqueness. ```php use Fabricate\Fabricate; // Configure a Japanese locale Faker Fabricate::config(function ($config) { $config->faker = \Faker\Factory::create('ja_JP'); }); $results = Fabricate::attributes_for('User', 3, function ($data, $world) { return [ 'user' => $world->faker()->userName, 'email' => $world->faker()->safeEmail, ]; }); // $results[0]['user'] => e.g. "yamada_taro" // $results[0]['email'] => e.g. "taro.yamada@example.net" ``` ```php // Mix Faker with sequences for guaranteed uniqueness $results = Fabricate::attributes_for('User', 5, function ($data, $world) { return [ 'user' => $world->faker()->firstName . $world->sequence('user_id'), 'email' => $world->sequence('email', function ($i) { return "test{$i}@example.com"; }), ]; }); ``` -------------------------------- ### Build a Single Record Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Use `Fabricate::build` to create a single object instance with custom attributes defined by a callback. The result is not persisted to the database. ```php $result = Fabricate::build('Post', function($data){ return ["created" => "2013-10-09 12:40:28", "updated" => "2013-10-09 12:40:28"]; }); ``` -------------------------------- ### Define and Apply Traits in Fabricate Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Define a trait with attributes and apply it to a fabricating object. Traits group attributes for reuse. ```php Fabricate::define(['trait'=>'published'], ['published'=>'1']); Fabricate::create('Post', function($data, $world) { $world->traits('published'); return ['author_id'=>5]; }); ``` -------------------------------- ### Generate Fake Data with Faker in Fabricate Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Use the configured Faker instance within Fabricate to generate fake data, like a user's name. The Faker configuration is optional and can be overridden. ```php Fabricate::config(function($config) { $config->faker = Faker\Factory::create('ja_JP'); // this is optional }); $results = Fabricate::attributes_for('User', function($data, $world){ return [ 'user'=> $world->faker()->name ]; }); ``` -------------------------------- ### Check for Whitespace Errors Source: https://github.com/sizuhiko/fabricate/blob/develop/CONTRIBUTING.markdown Before committing, run this command to check for unnecessary whitespace errors in your changes. This helps maintain code quality. ```bash git diff --check ``` -------------------------------- ### Define Multiple Traits for Fabricate Objects Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Define multiple traits, including one with a closure for dynamic attribute generation, and apply them to a fabricating object. This allows for more complex attribute grouping. ```php Fabricate::define(['trait'=>'published'], ['published'=>'1']); Fabricate::define(['trait'=>'author5'], function($data, $world) { return ['author_id'=>5]; }); Fabricate::create('Post', function($data, $world) { $world->traits(['published','author5']); return []; }); ``` -------------------------------- ### Define Model Schema with `FabricateModel` Source: https://context7.com/sizuhiko/fabricate/llms.txt Use `FabricateModel` to define model schemas with columns and associations. This schema is passed to an adaptor for generating type-appropriate fake values. ```php use Fabricate\Model\FabricateModel; $model = (new FabricateModel('Article')) ->addColumn('id', 'integer') ->addColumn('user_id', 'integer', ['null' => false]) ->addColumn('title', 'string', ['null' => false, 'limit' => 120]) ->addColumn('slug', 'string', ['null' => false, 'limit' => 120]) ->addColumn('body', 'text') ->addColumn('view_count', 'integer') ->addColumn('rating', 'float') ->addColumn('is_published', 'boolean') ->addColumn('published_at', 'datetime') ->addColumn('created', 'datetime') ->addColumn('updated', 'datetime') // Associations ->belongsTo('Author', 'user_id', 'User') // Article belongsTo User (aliased as Author) ->hasMany('Comment', 'article_id') // Article hasMany Comment ->hasOne('ArticleMeta', 'article_id'); // Article hasOne ArticleMeta // Retrieve schema metadata $columns = $model->getColumns(); // ['id' => ['type'=>'integer','options'=>[]], ...] $name = $model->getName(); // 'Article' $associated = $model->getAssociated(); // ['Author' => 'belongsTo', 'Comment' => 'hasMany', ...] ``` -------------------------------- ### Register Named Factory Definitions with Fabricate::define Source: https://context7.com/sizuhiko/fabricate/llms.txt Register reusable factory definitions under a custom name. Definitions can be mapped to specific model classes or inherit from parent definitions. ```php use Fabricate\Fabricate; // Simple named definition that maps directly to a model class Fabricate::define('Post', ['published' => '1']); // Definition with a custom name mapped to a different model class Fabricate::define(['PublishedPost', 'class' => 'Post'], ['published' => '1']); // Definition inheriting from a parent (merges parent attributes) Fabricate::define(['PublishedPost', 'class' => 'Post'], ['published' => '1']); Fabricate::define(['Author5Published', 'parent' => 'PublishedPost'], ['author_id' => 5]); $results = Fabricate::attributes_for('Author5Published'); // $results[0]['published'] === '1' // $results[0]['author_id'] === 5 ``` ```php // Definition using a callback for dynamic attribute generation Fabricate::define(['ActiveUser', 'class' => 'User'], function ($data, $world) { return [ 'user' => $world->faker()->userName, 'password' => md5($world->sequence('user_seq', function ($i) { return "password_{$i}"; })), ]; }); $user = Fabricate::attributes_for('ActiveUser'); // $user[0]['user'] is a Faker-generated username ``` -------------------------------- ### Run CakePHP Coding Standards Sniffs Source: https://github.com/sizuhiko/fabricate/blob/develop/CONTRIBUTING.markdown Apply the CakePHP coding standards to your project's PHP files using the phpcs command. This command checks for compliance with the standard. ```bash phpcs -p --extensions=php --standard=CakePHP ./app/Plugin/Fabricate ``` -------------------------------- ### Fabricate::define Source: https://context7.com/sizuhiko/fabricate/llms.txt Registers named factory definitions for reusable attribute sets. ```APIDOC ## `Fabricate::define($name, $define)` — Register named factory definitions Registers a reusable factory under a custom name, optionally tied to a different model class (`class` key) or inheriting from a parent definition (`parent` key). Defined factories can be referenced anywhere by their registered name. ### Parameters - **$name** (string|array) - The name of the definition, or an array containing the name and optional `class` or `parent` keys. - **$define** (array|callable) - An array of attributes or a callback function to define the factory. ### Request Example ```php use Fabricate\Fabricate; // Simple named definition that maps directly to a model class Fabricate::define('Post', ['published' => '1']); // Definition with a custom name mapped to a different model class Fabricate::define(['PublishedPost', 'class' => 'Post'], ['published' => '1']); // Definition inheriting from a parent (merges parent attributes) Fabricate::define(['PublishedPost', 'class' => 'Post'], ['published' => '1']); Fabricate::define(['Author5Published', 'parent' => 'PublishedPost'], ['author_id' => 5]); // Definition using a callback for dynamic attribute generation Fabricate::define(['ActiveUser', 'class' => 'User'], function ($data, $world) { return [ 'user' => $world->faker()->userName, 'password' => md5($world->sequence('user_seq', function ($i) { return "password_{$i}"; })), ]; }); ``` ### Response Example (when using `attributes_for`) ```json [ { "published": "1" } ] ``` ```json [ { "published": "1", "author_id": 5 } ] ``` ```json [ { "user": "generated_username", "password": "generated_md5_hash" } ] ``` ``` -------------------------------- ### Configure Faker Locale in Fabricate Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Configure the Faker generator to use a specific locale, such as Japanese ('ja_JP'). This affects how fake data is generated. ```php Fabricate::config(function($config) { $config->faker = Faker\Factory::create('ja_JP'); }); ``` -------------------------------- ### Generate Attributes with Sequences Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Use `Fabricate::attributes_for` with `$world->sequence()` to generate attributes with unique, sequential values. The sequence can be a simple increment or use a callback for custom value generation. ```php Fabricate::config(function($config) { $config->sequence_start = 100; }); $results = Fabricate::attributes_for('Post', 10, function($data, $world){ return [ 'id'=> $world->sequence('id'), 'title'=> $world->sequence('title', 1, function($i){ return "Title {$i}"; }) ]; }); ``` -------------------------------- ### Fabricate::define(['trait' => $name], $define) Source: https://context7.com/sizuhiko/fabricate/llms.txt Registers reusable trait definitions that can be applied within generation callbacks. ```APIDOC ## `Fabricate::define(['trait' => $name], $define)` — Register reusable trait definitions Defines a named trait (a reusable group of attributes) that can be applied inside any generation callback via `$world->traits()`. Traits are merged into the generated attributes at fabrication time. ### Parameters - **$name** (string) - The name of the trait. - **$define** (array|callable) - An array of attributes or a callback function defining the trait. ### Request Example ```php use Fabricate\Fabricate; // Register traits Fabricate::define(['trait' => 'published'], ['published' => '1']); Fabricate::define(['trait' => 'author5'], function ($data, $world) { return ['author_id' => 5]; }); // Apply a single trait inside a callback $results = Fabricate::attributes_for('Post', function ($data, $world) { $world->traits('published'); return ['title' => 'Trait Test']; }); // Apply multiple traits at once $results = Fabricate::attributes_for('Post', function ($data, $world) { $world->traits(['published', 'author5']); return []; }); ``` ### Response Example (when using `attributes_for`) ```json [ { "published": "1", "title": "Trait Test" } ] ``` ```json [ { "published": "1", "author_id": 5 } ] ``` ``` -------------------------------- ### Clear Fabricate State Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Reset the Fabricate library to its original state. This is useful for clearing loaded definitions and configurations. ```php Fabricate::clear(); ``` -------------------------------- ### Define Object Attributes Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Use `Fabricate::define` to set default attributes for a model. This can be done directly with an array or using a callback for dynamic attribute generation. The 'class' key can be used to specify a different class name. ```php Fabricate::define('Post', ['published'=>'1']); ``` ```php // or using callback block Fabricate::define('Post', function($data, $world) { return ['published'=>'1'] }); ``` ```php Fabricate::define(['PublishedPost', 'class'=>'Post'], ['published'=>'1']); ``` ```php Fabricate::create('PublishedPost'); ``` -------------------------------- ### Generate Nested Associations with `$world->association()` Source: https://context7.com/sizuhiko/fabricate/llms.txt Use `$world->association()` within `create` or `attributes_for` callbacks to generate nested association data. It automatically handles `hasMany`, `hasOne`, and `belongsTo` relationships. `belongsTo` returns a single array, while `hasMany` returns an array of records. A custom defined factory name can be used by passing an array like `['DefinedName', 'association' => 'ModelName']`. ```php use Fabricate\Fabricate; // hasMany: User with 3 Posts, each Post with 2 PostTags and a Tag $result = Fabricate::create('User', function ($data, $world) { return [ 'user' => 'taro', 'Post' => $world->association('Post', 3, [ 'id' => false, // suppress auto-id 'author_id' => false, 'PostTag' => $world->association('PostTag', 2, [ 'post_id' => false, 'tag_id' => false, 'Tag' => $world->association('Tag'), ]), ]), ]; }); // $result['User']['user'] === 'taro' // count($result['User']['Post']) === 3 // count($result['User']['Post'][0]['PostTag']) === 2 // $result['User']['Post'][0]['PostTag'][0]['Tag'] is non-empty ``` ```php // Use a defined factory for the association Fabricate::define(['PublishedPost', 'class' => 'Post'], ['published' => '1']); $result = Fabricate::create('User', function ($data, $world) { return [ 'user' => 'hanako', 'Post' => $world->association( ['PublishedPost', 'association' => 'Post'], 2, ['id' => false, 'author_id' => false] ), ]; }); // All posts will have published === '1' ``` ```php // belongsTo: create Posts that each belong to a specific Author Fabricate::define(['PublishedPost', 'class' => 'Post'], ['published' => '1']); $results = Fabricate::create('PublishedPost', 3, function ($data, $world) { return [ 'Author' => $world->association( ['User', 'association' => 'Author'], ['id' => 1, 'user' => 'admin'] ), ]; }); // $results[0]['Post']['Author']['user'] === 'admin' ``` -------------------------------- ### Register Reusable Trait Definitions with Fabricate::define(['trait' => $name]) Source: https://context7.com/sizuhiko/fabricate/llms.txt Define named traits (reusable attribute groups) that can be applied within generation callbacks using `$world->traits()`. Traits are merged into attributes at fabrication time. ```php use Fabricate\Fabricate; // Register traits Fabricate::define(['trait' => 'published'], ['published' => '1']); Fabricate::define(['trait' => 'author5'], function ($data, $world) { return ['author_id' => 5]; }); // Apply a single trait inside a callback $results = Fabricate::attributes_for('Post', function ($data, $world) { $world->traits('published'); return ['title' => 'Trait Test']; }); // $results[0]['published'] === '1' ``` ```php // Apply multiple traits at once $results = Fabricate::attributes_for('Post', function ($data, $world) { $world->traits(['published', 'author5']); return []; }); // $results[0]['published'] === '1' // $results[0]['author_id'] === 5 ``` -------------------------------- ### Generate Attribute Arrays for Models Source: https://context7.com/sizuhiko/fabricate/llms.txt Generates one or more attribute arrays derived from the model schema without saving to a database or instantiating a model class. Useful for unit tests that only need raw data arrays. The optional third argument can be an array or a closure to override specific fields. ```php use Fabricate\Fabricate; // Generate 10 Post attribute arrays, overriding timestamps via callback $posts = Fabricate::attributes_for('Post', 10, function ($data, $world) { return [ 'created' => '2024-01-15 09:00:00', 'updated' => '2024-01-15 09:00:00', ]; }); // $posts[0] => ['id' => 1, 'author_id' => 1, 'title' => '<50-char string>', // 'body' => '', 'published' => '<1 char>', // 'created' => '2024-01-15 09:00:00', 'updated' => '2024-01-15 09:00:00'] // Generate using an override array instead of a callback $posts = Fabricate::attributes_for('Post', 5, ['published' => '1']); // Generate a single record (default count = 1) $single = Fabricate::attributes_for('Post'); // Returns an array of 1 element: $single[0]['id'] === 1 ``` -------------------------------- ### Generate Model Attributes as Array Source: https://github.com/sizuhiko/fabricate/blob/develop/README.md Generate an array of model attributes without saving them to the database. This is useful for testing or further manipulation. ```php $results = Fabricate::attributes_for('Post', 10, function($data){ return ["created" => "2013-10-09 12:40:28", "updated" => "2013-10-09 12:40:28"]; }); ``` -------------------------------- ### Fabricate::attributes_for Source: https://context7.com/sizuhiko/fabricate/llms.txt Generates one or more attribute arrays for a given model, without persisting them to a database or instantiating model classes. This is useful for unit tests requiring raw data. ```APIDOC ## Fabricate::attributes_for($modelName, $count, $callbackOrArray) ### Description Generates one or more attribute arrays derived from the model schema, without saving to a database or instantiating a model class. Useful for unit tests that only need raw data arrays. The optional third argument can be an array or a closure receiving `($data, $world)` to override specific fields. ### Method `Fabricate::attributes_for` ### Parameters - **$modelName** (string) - The name of the model to generate attributes for. - **$count** (integer, optional) - The number of attribute arrays to generate. Defaults to 1. - **$callbackOrArray** (callable|array, optional) - An array or a callback function to override specific fields. The callback receives `($data, $world)`. ### Request Example ```php use Fabricate\Fabricate; // Generate 10 Post attribute arrays, overriding timestamps via callback $posts = Fabricate::attributes_for('Post', 10, function ($data, $world) { return [ 'created' => '2024-01-15 09:00:00', 'updated' => '2024-01-15 09:00:00', ]; }); // $posts[0] => ['id' => 1, 'author_id' => 1, 'title' => '<50-char string>', // 'body' => '', 'published' => '<1 char>', // 'created' => '2024-01-15 09:00:00', 'updated' => '2024-01-15 09:00:00'] // Generate using an override array instead of a callback $posts = Fabricate::attributes_for('Post', 5, ['published' => '1']); // Generate a single record (default count = 1) $single = Fabricate::attributes_for('Post'); // Returns an array of 1 element: $single[0]['id'] === 1 ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.