### Install Composer Dependencies Source: https://factory-muffin.thephpleague.com/contributing Run this command to install the necessary dependencies for development and testing. ```bash $ composer install ``` -------------------------------- ### Install Factory Muffin 1.6.* Source: https://factory-muffin.thephpleague.com/upgrading/1.6 Add this to your composer.json require-dev section to install version 1.6.* of Factory Muffin. ```json { "require-dev": { "league/factory-muffin": "1.6.*" } } ``` -------------------------------- ### Install Factory Muffin 2.1 Source: https://factory-muffin.thephpleague.com/upgrading/2.1 Add this to your composer.json file to install version 2.1.* of Factory Muffin as a development dependency. ```json { "require-dev": { "league/factory-muffin": "2.1.*" } } ``` -------------------------------- ### Get Factory Instance Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Facade.html Returns the cached underlying factory instance. ```php factory() : \League\FactoryMuffin\Factory ``` -------------------------------- ### get() Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Arr.html Retrieves an item from an array based on the provided key. ```APIDOC ## get() ### Description Get an item from an array. ### Parameters #### Path Parameters - **array** (array) - Required - The source array - **key** (string) - Required - The key to retrieve ### Response - **Returns** (mixed) - The value associated with the key or null if not found. ``` -------------------------------- ### Get Model Method Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.ModelException.html Signature for retrieving the model associated with the exception. ```php getModel() : string ``` -------------------------------- ### Get pending objects Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html Return an array of objects to be saved. ```php pending() : array ``` -------------------------------- ### Define Model Relationships with Factory Generator Source: https://factory-muffin.thephpleague.com/usage/generators Use the factory generator to set up relationships between models. This example defines a 'Foo' model with a 'bar_id' that references a generated 'Bar' model. ```php League\FactoryMuffin\Facade::define('Foo', array( 'bar_id' => 'factory|Bar' )); League\FactoryMuffin\Facade::define('Bar', array( 'baz' => 'date|Y-m-d' )); ``` -------------------------------- ### Get saved objects Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html Return an array of saved objects. ```php saved() : array ``` -------------------------------- ### Faker Instance Retrieval Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html Information on how to get the Faker generator instance used by Factory Muffin. ```APIDOC ## GET /faker ### Description Retrieves the Faker generator instance. If the instance has not been created yet, it will be initialized with the configured locale. ### Method GET ### Endpoint /faker ### Parameters None ### Request Example ``` GET /faker ``` ### Response #### Success Response (200) - **faker** (object) - The Faker generator instance. #### Response Example ```json { "faker_instance": "" } ``` ``` -------------------------------- ### Test Model with Factory Muffin Source: https://factory-muffin.thephpleague.com/usage/examples Set up and use Factory Muffin within a PHPUnit test class. This example loads factories, creates a 'Message' object, asserts its type and the type of its associated 'user', and cleans up by deleting saved objects. ```php # tests/TestUserModel.php use League\FactoryMuffin\Facade as FactoryMuffin; class TestUserModel extends PHPUnit_Framework_TestCase { public static function setupBeforeClass() { // note that method chaining is supported FactoryMuffin::setFakerLocale('en_EN')->setSaveMethod('save'); // optional step FactoryMuffin::loadFactories(__DIR__ . '/factories'); } public function testSampleFactory() { $message = FactoryMuffin::create('Message'); $this->assertInstanceOf('Message', $message); $this->assertInstanceOf('User', $message->user); } public static function tearDownAfterClass() { FactoryMuffin::setDeleteMethod('delete'); // optional step FactoryMuffin::deleteSaved(); } } ``` -------------------------------- ### Call Static Method on Factory-Generated Model Source: https://factory-muffin.thephpleague.com/usage/generators Set the 'baz' attribute by calling a method on a model generated via the factory. This example calls 'exampleMethod' on 'OtherModel' after it's generated. ```php League\FactoryMuffin\Facade::define('MyModel', array( 'baz' => 'call|exampleMethod|factory|OtherModel', )); League\FactoryMuffin\Facade::define('OtherModel', array( 'example' => 'boolean', )); ``` -------------------------------- ### Call Static Model Methods for Attributes Source: https://factory-muffin.thephpleague.com/usage/generators Use the call generator to set an attribute by calling a static method on a model. This example calls 'MyModel::exampleMethod()'. ```php League\FactoryMuffin\Facade::define('MyModel', array( 'foo' => 'call|exampleMethod', )); ``` -------------------------------- ### Retrieve model instances and attributes Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Facade.html Methods to get model instances or mock attributes without persisting to the database. ```php instance(string $model, array $attr = array() : object ``` ```php attributesFor(object $object, array $attr = array() : array ``` -------------------------------- ### Create Multiple Models Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html Generates and saves multiple instances of a specified model with given attributes. This method is intended for use after initial setup via the facade. ```php public function create($times, $model, array $attr = array()) { // ... implementation details omitted for brevity ... ``` -------------------------------- ### Get Method Name Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.DeleteMethodNotFoundException.html Retrieves the name of the method that was not found. This is useful for debugging or logging purposes. ```php public function getMethod(): string ``` -------------------------------- ### Factory Muffin - Get Faker Instance Source: https://factory-muffin.thephpleague.com/api/files/Factory.html Retrieves the Faker generator instance. If it hasn't been created yet, it will be initialized with the specified locale. ```APIDOC ## GET /faker ### Description Get the faker instance. Initializes it if it does not exist. ### Method GET ### Endpoint /faker ### Response #### Success Response (200) - **faker** (object) - The Faker generator instance. #### Response Example ```json { "faker": "" } ``` ``` -------------------------------- ### Get Model Instance Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.DeleteMethodNotFoundException.html Retrieves the model instance that caused the exception. This can be used to inspect the state of the model. ```php public function getObject(): object ``` -------------------------------- ### Make a model instance Source: https://factory-muffin.thephpleague.com/api/files/Factory.html Instantiates a model, applies attributes, and handles pending state tracking. ```php private function make($model, array $attr, $save) { $group = $this->getGroup($model); $class = $this->getModelClass($model, $group); $object = $this->makeClass($class); // Make the object as saved so that other generators persist correctly if ($save) { Arr::add($this->pending, $object); } // Get the group specific factory attributes if ($group) { $attr = array_merge($attr, $this->getFactoryAttrs($model)); } // Get the factory attributes for that model $attributes = $this->attributesFor($object, $attr); foreach ($attributes as $name => $value) { $this->setAttribute($object, $name, $value); } return $object; } ``` -------------------------------- ### Instantiate a class Source: https://factory-muffin.thephpleague.com/api/files/Factory.html Creates a new instance of the specified class, optionally using a custom maker. ```php private function makeClass($class) { if (!class_exists($class)) { throw new ModelNotFoundException($class); } if ($maker = $this->customMaker) { return $maker($class); } return new $class(); } ``` -------------------------------- ### Run Unit Tests with PHPUnit Source: https://factory-muffin.thephpleague.com/contributing Execute this command to run the project's test suite using PHPUnit. ```bash $ vendor/bin/phpunit ``` -------------------------------- ### Load factory files Source: https://factory-muffin.thephpleague.com/usage/definitions Includes all factory definition files from a specified directory. ```php League\FactoryMuffin\Facade::loadFactories(__DIR__ . '/factories'); ``` -------------------------------- ### Get Errors Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.SaveFailedException.html Retrieves any associated error messages from the exception. ```php public function getErrors(): string ``` -------------------------------- ### Construct the exception Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.DirectoryNotFoundException.html Initializes a new instance of the exception with the invalid path. ```php __construct(string $path, string|null $message = null) : void ``` -------------------------------- ### Create and persist a model instance Source: https://factory-muffin.thephpleague.com/api/files/Factory.html Creates a new model instance, saves it to the database, and triggers any associated callbacks. ```php public function create($model, array $attr = array()) { $object = $this->make($model, $attr, true); $this->persist($object); if ($this->triggerCallback($object)) { $this->persist($object); } return $object; } ``` -------------------------------- ### Get array item signature Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Arr.html Retrieves an item from an array by key. ```php get(array $array, string $key) : mixed ``` -------------------------------- ### Configuration Methods Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html Methods to configure the behavior of the FactoryMuffin instance, including localization and custom lifecycle methods. ```APIDOC ## Configuration Methods ### Description Methods to configure the behavior of the FactoryMuffin instance, including localization and custom lifecycle methods. ### Parameters #### setFakerLocale - **local** (string) - Required - The faker locale (e.g., 'en_EN'). #### setSaveMethod - **method** (string) - Required - The name of the method to call when saving objects. #### setDeleteMethod - **method** (string) - Required - The name of the method to call when deleting objects. #### setCustomMaker - **maker** (Closure) - Required - A custom closure for creating models. #### setCustomSetter - **setter** (Closure) - Required - A custom closure for setting attributes. #### setCustomSaver - **saver** (Closure) - Required - A custom closure for saving models. #### setCustomDeleter - **deleter** (Closure) - Required - A custom closure for deleting models. ``` -------------------------------- ### Get Model Name Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.SaveFailedException.html Retrieves the name of the model associated with the exception. ```php public function getModel(): string ``` -------------------------------- ### Facade Class Implementation Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Facade.html The main entry point class that proxies static method calls to the underlying factory instance. ```php * @author Scott Robertson * @author Graham Campbell * @license MIT */ class Facade { /** * The underlying factory instance. * * @var \League\FactoryMuffin\Factory */ private static $factory; /** * Get the underlying factory instance. * * We'll always cache the instance and reuse it. * * @return \League\FactoryMuffin\Factory */ private static function factory() { if (!self::$factory) { self::$factory = new Factory(); } return self::$factory; } /** * Reset the underlying factory instance. * * @return \League\FactoryMuffin\Factory */ public static function reset() { self::$factory = null; return self::factory(); } /** * Handle dynamic, static calls to the object. * * @codeCoverageIgnore * * @param string $method * @param array $args * * @return mixed */ public static function __callStatic($method, $args) { switch (count($args)) { case 0: return self::factory()->$method(); case 1: return self::factory()->$method($args[0]); case 2: return self::factory()->$method($args[0], $args[1]); case 3: return self::factory()->$method($args[0], $args[1], $args[2]); default: return call_user_func_array(array(self::factory(), $method), $args); } } } ``` -------------------------------- ### Create and Persist a Single Model Instance Source: https://factory-muffin.thephpleague.com/api/files/Factory.html The `create` method generates a model instance with mock attributes, persists it to the database, and optionally triggers a callback. It returns the created model instance. ```APIDOC ## POST /api/create ### Description Creates and saves a single model instance to the database with mock attributes. ### Method POST ### Endpoint /api/create ### Parameters #### Query Parameters - **model** (string) - Required - The class name of the model to create. - **attr** (array) - Optional - An array of attributes to set on the model instance. ### Request Example ```json { "model": "Product", "attr": { "name": "Awesome Gadget", "price": 99.99 } } ``` ### Response #### Success Response (200) - **object** (object) - The created and persisted model instance. #### Response Example ```json { "object": { "id": 1, "name": "Awesome Gadget", "price": 99.99 } } ``` ``` -------------------------------- ### Get model class name Source: https://factory-muffin.thephpleague.com/api/files/Factory.html Removes the group prefix from a model class name string. ```php private function getModelClass($model, $group) { if ($group) { return str_replace($group.':', '', $model); } return $model; } ``` -------------------------------- ### Create and save model Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html Creates and saves in db an instance of the model. ```php create(string $model, array $attr = array()) : object ``` -------------------------------- ### Get model group name Source: https://factory-muffin.thephpleague.com/api/files/Factory.html Extracts the group prefix from a model class name string. ```php private function getGroup($model) { if (strpos($model, ':') !== false) { return current(explode(':', $model)); } } ``` -------------------------------- ### Facade Class Source: https://factory-muffin.thephpleague.com/api/namespaces/League.FactoryMuffin.html Provides a simplified interface to underlying components. ```APIDOC ## Facade Class ### Description This class acts as a facade, offering a simplified interface to the functionalities within the LeagueFactoryMuffin project. ### Methods (No specific methods detailed in the provided text) ### Parameters (No specific parameters detailed in the provided text) ### Request Body (Not applicable for this class) ### Response (Not applicable for this class) ``` -------------------------------- ### Configuration Methods Source: https://factory-muffin.thephpleague.com/api/files/Factory.html Methods to configure the behavior of the Factory class, such as setting the faker locale, save/delete methods, and custom closures. ```APIDOC ## Configuration Methods ### Description Configures the Factory instance settings. ### Parameters #### Request Body - **local** (string) - Required - The faker locale (e.g., 'en_EN'). - **method** (string) - Required - The method name to use for saving or deleting. - **maker/setter/saver/deleter** (Closure) - Required - Custom logic closures for model operations. ``` -------------------------------- ### Factory Class Source: https://factory-muffin.thephpleague.com/api/namespaces/League.FactoryMuffin.html Handles the creation of objects. ```APIDOC ## Factory Class ### Description This class is responsible for the creation and instantiation of objects within the LeagueFactoryMuffin framework. ### Methods (No specific methods detailed in the provided text) ### Parameters (No specific parameters detailed in the provided text) ### Request Body (Not applicable for this class) ### Response (Not applicable for this class) ``` -------------------------------- ### Method: getPrefix() Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Generators.Base.html Returns the prefix applied to the generator kind, such as 'unique' or 'optional'. Returns a string. ```php getPrefix() : string ``` -------------------------------- ### POST /factory/create Source: https://factory-muffin.thephpleague.com/api/files/Factory.html Generates multiple versions of an object and saves them to the database. ```APIDOC ## POST /factory/create ### Description Generates multiple versions of an object and saves them to the database. ### Parameters #### Request Body - **times** (int) - Required - The number of models to create. - **model** (string) - Required - The model class name. - **attr** (array) - Optional - The model attributes. ``` -------------------------------- ### Factory Muffin - Load Factories Source: https://factory-muffin.thephpleague.com/api/files/Factory.html Loads factory definitions from one or more directories. Each PHP file in the specified directories should contain factory definitions. ```APIDOC ## POST /factories/load ### Description Load the specified factories. This method expects either a single path to a directory containing php files, or an array of directory paths, and will include_once every file. These files should contain factory definitions for your models. ### Method POST ### Endpoint /factories/load ### Parameters #### Request Body - **paths** (string|string[]) - Required - The directory path(s) to load factory definitions from. ### Request Example ```json { "paths": "/path/to/factories" } ``` ```json { "paths": [ "/path/to/factories1", "/path/to/factories2" ] } ``` ### Response #### Success Response (200) - **$this** (object) - Returns the current instance for method chaining. #### Response Example ```json { "message": "Factories loaded successfully" } ``` ### Error Handling - **DirectoryNotFoundException**: Thrown if a specified path is not a directory. ``` -------------------------------- ### POST /factory/create Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html Creates and saves a new instance of a model to the database with optional attributes. ```APIDOC ## POST /factory/create ### Description Creates and saves an instance of the specified model to the database, applying mock attributes and triggering any defined callbacks. ### Method POST ### Parameters #### Request Body - **model** (string) - Required - The model class name. - **attr** (array) - Optional - The model attributes to override. ### Response #### Success Response (200) - **object** (object) - The created and persisted model instance. ``` -------------------------------- ### Load Factory Definitions Source: https://factory-muffin.thephpleague.com/api/files/Factory.html Loads factory files from one or more directory paths. Throws a DirectoryNotFoundException if a provided path is invalid. ```php public function loadFactories($paths) { foreach ((array) $paths as $path) { if (!is_dir($path)) { throw new DirectoryNotFoundException($path); } $this->loadDirectory($path); } return $this; } ``` -------------------------------- ### Get Model Class Name Source: https://factory-muffin.thephpleague.com/api/files/Factory.html The `getModelClass` method returns the actual model class name by removing any group prefix if present. It takes the model name and its group as input. ```APIDOC ## GET /api/get-model-class ### Description Retrieves the base model class name by removing any group prefix. ### Method GET ### Endpoint /api/get-model-class ### Parameters #### Query Parameters - **model** (string) - Required - The model class name, potentially with a group prefix. - **group** (string|null) - Optional - The group name of the model. ### Request Example ```json { "model": "users:Admin", "group": "users" } ``` ### Response #### Success Response (200) - **modelClass** (string) - The base model class name without the group prefix. #### Response Example ```json { "modelClass": "Admin" } ``` ``` -------------------------------- ### Factory Definition and Loading Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html Methods for defining new model factories and loading factory files from directories. ```APIDOC ## define(string $model, array $definition = array(), \Closure|null $callback = null) ### Description Define a new model factory. ### Parameters - **model** (string) - Required - The model class name. - **definition** (array) - Required - The attribute definitions. - **callback** (\Closure|null) - Optional - The closure callback. ## loadFactories(string|array $paths) ### Description Load the specified factories from directory paths. ### Parameters - **paths** (string|array) - Required - The directory path(s) to load. ### Throws - \League\FactoryMuffin\Exceptions\DirectoryNotFoundException ``` -------------------------------- ### Factory Muffin Factory Methods Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html This section details the methods available in the Factory Muffin Factory class. ```APIDOC ## Methods ### setFakerLocale() __``` setFakerLocale(string $local) : $this ``` _Set the faker locale._ #### Parameters string | $local | The faker locale. ---|---|--- #### Returns $this ### setSaveMethod() __``` setSaveMethod(string $method) : $this ``` _Set the method we use when saving objects._ #### Parameters string | $method | The save method name. ---|---|--- #### Returns $this ### setDeleteMethod() __``` setDeleteMethod(string $method) : $this ``` _Set the method we use when deleting objects._ #### Parameters string | $method | The delete method name. ---|---|--- #### Returns $this ### setCustomMaker() __``` setCustomMaker(\Closure $maker) : $this ``` _Set the custom maker closure._ #### Parameters \Closure | $maker | ---|---|--- #### Returns $this ### setCustomSetter() __``` setCustomSetter(\Closure $setter) : $this ``` _Set the custom setter closure._ #### Parameters \Closure | $setter | ---|---|--- #### Returns $this ### setCustomSaver() __``` setCustomSaver(\Closure $saver) : $this ``` _Set the custom saver closure._ #### Parameters \Closure | $saver | ---|---|--- #### Returns $this ### setCustomDeleter() __``` setCustomDeleter(\Closure $deleter) : $this ``` _Set the custom deleter closure._ #### Parameters \Closure | $deleter | ---|---|--- #### Returns $this ### seed() __``` seed(integer $times, string $model, array $attr = array()) : array ``` _Returns multiple versions of an object._ These objects are generated by the create function, so are saved to the database. #### Parameters integer | $times | The number of models to create. ---|---|--- string | $model | The model class name. array | $attr | The model attributes. #### Returns array ### create() __``` create(string $model, array $attr = array()) : object ``` _Creates and saves in db an instance of the model._ This object will be generated with mock attributes. #### Parameters string | $model | The model class name. ---|---|--- array | $attr | The model attributes. #### Returns object ### pending() __``` pending() : array ``` _Return an array of objects to be saved._ #### Returns array ### isPending() __``` isPending(object $object) : boolean ``` _Is the object going to be saved?_ #### Parameters object | $object | The model instance. ---|---|--- #### Returns boolean ### saved() __``` saved() : array ``` _Return an array of saved objects._ #### Returns array ### isSaved() __``` isSaved(object $object) : boolean ``` _Is the object saved?_ #### Parameters object | $object | The model instance. ---|---|--- #### Returns boolean ``` -------------------------------- ### Get Model Group Source: https://factory-muffin.thephpleague.com/api/files/Factory.html The `getGroup` method determines and returns the group name for a factory definition if the model class name includes a group prefix (e.g., 'group:ModelName'). Returns null if no group is specified. ```APIDOC ## GET /api/get-group ### Description Retrieves the group name associated with a model class name. ### Method GET ### Endpoint /api/get-group ### Parameters #### Query Parameters - **model** (string) - Required - The model class name, potentially including a group prefix (e.g., 'group:ModelName'). ### Request Example ```json { "model": "users:Admin" } ``` ### Response #### Success Response (200) - **group** (string|null) - The group name if specified, otherwise null. #### Response Example ```json { "group": "users" } ``` ``` -------------------------------- ### Model Instance Management Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html Methods for creating, instantiating, and retrieving model attributes. ```APIDOC ## instance(string $model, array $attr = array()) ### Description Return an instance of the model without saving it to the database. ### Parameters - **model** (string) - Required - The model class name. - **attr** (array) - Optional - The model attributes. ## make(string $model, array $attr, boolean $save) ### Description Make an instance of the model. ### Parameters - **model** (string) - Required - The model class name. - **attr** (array) - Required - The model attributes. - **save** (boolean) - Required - Are we saving, or just creating an instance? ``` -------------------------------- ### loadDirectory() Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html Loads all factory definition files located within a specified directory path. ```APIDOC ## loadDirectory() ### Description Load all the files in a directory to register factory definitions. ### Parameters #### Path Parameters - **path** (string) - Required - The directory path to load. ### Throws - \League\FactoryMuffin\Exceptions\NoDefinedFactoryException ### Returns - **void** ``` -------------------------------- ### Create and save models Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Facade.html Creates and persists an instance of the model to the database. ```php create(string $model, array $attr = array() : object ``` -------------------------------- ### Factory Muffin Facade Methods Source: https://factory-muffin.thephpleague.com/api/files/Facade.html The Facade provides static access to various factory operations including defining models, creating instances, and managing saved objects. ```APIDOC ## Static Methods ### define(string $model, array $definition) - **Description**: Define a new model factory. ### create(string $model, array $attr) - **Description**: Creates and saves an instance of the model in the database. ### seed(int $times, string $model, array $attr) - **Description**: Returns multiple versions of an object. ### instance(string $model, array $attr) - **Description**: Return an instance of the model without saving it. ### deleteSaved() - **Description**: Call the delete method on any saved objects. ### loadFactories(string|string[] $paths) - **Description**: Load the specified factory files from the given paths. ### reset() - **Description**: Reset the underlying factory instance. ``` -------------------------------- ### Method: factory() Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Generators.Base.html Creates an instance of a specified model. If the model is configured to be saved, this instance will be automatically persisted to the database upon creation. ```php factory(string $model) : object ``` -------------------------------- ### Constructor: __construct() Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Generators.Base.html Initializes a new Generator instance. Requires the kind of attribute and optionally accepts a model instance and a Faker generator. ```php __construct(string $kind, object|null $object = null, \Faker\Generator|null $faker = null) : void ``` -------------------------------- ### Factory Loading API Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html This section details the methods for loading factory definitions into Factory Muffin. ```APIDOC ## POST /loadFactories ### Description Loads factory definitions from one or more directories. Each PHP file within the specified directories is included, expecting to contain factory definitions. ### Method POST ### Endpoint /loadFactories ### Parameters #### Request Body - **paths** (string|string[]) - Required - The directory path(s) containing factory definition files. ### Request Example ```json { "paths": "/path/to/factories" } ``` ### Response #### Success Response (200) - **$this** (object) - Returns the current instance for method chaining. #### Response Example ```json { "message": "Factories loaded successfully" } ``` ``` -------------------------------- ### Method: getOptions() Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Generators.Base.html Retrieves all options that were passed to the Generator, typically after a pipe symbol (|) in the attribute definition. Returns an array of options. ```php getOptions() : array ``` -------------------------------- ### Configure save and delete methods Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Facade.html Sets the methods used for saving or deleting objects. ```php setSaveMethod(string $method) : \League\FactoryMuffin\Factory ``` ```php setDeleteMethod(string $method) : \League\FactoryMuffin\Factory ``` -------------------------------- ### Make Model Instance Source: https://factory-muffin.thephpleague.com/api/files/Factory.html The `make` method creates an instance of a specified model class. It can optionally add the instance to a pending list for saving and merge group-specific or factory attributes. It returns the created model instance. ```APIDOC ## POST /api/make ### Description Creates an instance of a model class with specified attributes, optionally marking it for saving. ### Method POST ### Endpoint /api/make ### Parameters #### Request Body - **model** (string) - Required - The class name of the model to create. - **attr** (array) - Optional - An array of attributes to set on the model instance. - **save** (boolean) - Optional - If true, the instance is marked for saving. Defaults to false. ### Request Example ```json { "model": "User", "attr": {"name": "Test User"}, "save": true } ``` ### Response #### Success Response (200) - **object** (object) - The created model instance. #### Response Example ```json { "object": {"name": "Test User"} } ``` ``` -------------------------------- ### Constructor Definition Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.ModelException.html Signature for the ModelException constructor. ```php __construct(string $model, string $message) : void ``` -------------------------------- ### Retrieve the path Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.DirectoryNotFoundException.html Returns the path that caused the exception. ```php getPath() : string ``` -------------------------------- ### Load Model Factories Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Facade.html Loads factory definitions from the specified file paths. ```php loadFactories(string|array $paths) : \League\FactoryMuffin\Factory ``` -------------------------------- ### Define the path property Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.DirectoryNotFoundException.html Represents the directory path that was not found. ```php $path : string ``` -------------------------------- ### Factory Muffin Facade Methods Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Facade.html A collection of static methods available through the Facade class for managing model factories and object lifecycles. ```APIDOC ## getFaker() ### Description Retrieves the underlying Faker generator instance. ### Returns - **\Faker\Generator** - The faker instance. ## loadFactories(paths) ### Description Loads model factory definitions from the specified paths. ### Parameters #### Request Body - **paths** (string|array) - Required - The file path or array of paths to load factories from. ### Returns - **\League\FactoryMuffin\Factory** - The factory instance. ## create(model, attr) ### Description Creates and saves an instance of the specified model to the database. ### Parameters #### Request Body - **model** (string) - Required - The model class name. - **attr** (array) - Optional - Attributes to override. ### Returns - **object** - The created and saved model instance. ## seed(times, model, attr) ### Description Generates and saves multiple versions of an object. ### Parameters #### Request Body - **times** (int) - Required - Number of instances to create. - **model** (string) - Required - The model class name. - **attr** (array) - Optional - Attributes to override. ### Returns - **array** - An array of saved objects. ``` -------------------------------- ### Arr class implementation Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Arr.html Full source code for the Arr utility class. ```php * @author Graham Campbell * @license MIT */ class Arr { /** * Get an item from an array. * * @param array $array * @param string $key * * @return mixed */ public static function get(&$array, $key) { if (in_array($key, array_keys($array), true)) { return $array[$key]; } } /** * Is the item in the array. * * @param array $array * @param mixed $item * * @return bool */ public static function has(&$array, $item) { return in_array($item, $array, true); } /** * Add an object to an array. * * @param array $array * @param object $object * * @return void */ public static function add(&$array, $object) { $array[spl_object_hash($object)] = $object; } /** * Remove an object from an array. * * @param array $array * @param object $object * * @return void */ public static function remove(&$array, $object) { if (in_array($object, $array, true)) { unset($array[spl_object_hash($object)]); } } } ``` -------------------------------- ### Create Multiple Model Instances (Seed) Source: https://factory-muffin.thephpleague.com/api/files/Factory.html The `seed` method creates a specified number of model instances with given attributes and returns them as an array. It internally uses the `create` method for each instance. ```APIDOC ## POST /api/seed ### Description Creates and returns an array of model instances. ### Method POST ### Endpoint /api/seed ### Parameters #### Query Parameters - **times** (integer) - Required - The number of model instances to create. - **model** (string) - Required - The class name of the model to create. - **attr** (array) - Optional - An array of attributes to set on the model instances. ### Request Example ```json { "times": 5, "model": "User", "attr": { "name": "John Doe", "email": "john.doe@example.com" } } ``` ### Response #### Success Response (200) - **seeds** (array) - An array of created model instances. #### Response Example ```json { "seeds": [ { "id": 1, "name": "John Doe", "email": "john.doe@example.com" }, { "id": 2, "name": "Jane Smith", "email": "jane.smith@example.com" } ] } ``` ``` -------------------------------- ### Access the factory property Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Facade.html Retrieves the underlying factory instance. ```php $factory : \League\FactoryMuffin\Factory ``` -------------------------------- ### DirectoryNotFoundException Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.DirectoryNotFoundException.html This exception is thrown when attempting to load factory definitions from a non-existent directory. ```APIDOC ## Class: League\FactoryMuffin\ExceptionsDirectoryNotFoundException ### Description This is the directory not found exception class. It is thrown if you try to load factory definitions from a directory that doesn't exist. ### Properties #### $path - **$path** (string) - The path. ### Methods #### __construct(string $path, string|null $message = null) - **__construct** (string $path, string|null $message = null) - Create a new instance. - Parameters: - **$path** (string) - - **$message** (string|null) - #### getPath() - **getPath** () : string - Get the path. - Returns: - string ``` -------------------------------- ### Define $callbacks property Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html The array of callbacks to trigger on instance/create. ```php $callbacks : array ``` -------------------------------- ### Construct ModelNotFoundException Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.ModelNotFoundException.html Initializes a new instance of the exception with the model name and an optional message. ```php __construct(string $model, string|null $message = null) : void ``` -------------------------------- ### Define $customMaker property Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html This is the custom model maker closure. ```php $customMaker : \Closure ``` -------------------------------- ### Persistence and Lifecycle Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html Methods for saving, deleting, and managing the lifecycle of model instances. ```APIDOC ## persist(object $object) ### Description Save the object to the database. ### Parameters - **object** (object) - Required - The model instance. ### Throws - \League\FactoryMuffin\Exceptions\SaveFailedException ## delete(object $object) ### Description Delete our object from the db. ### Parameters - **object** (object) - Required - The model instance. ### Throws - \League\FactoryMuffin\Exceptions\DeleteMethodNotFoundException ``` -------------------------------- ### Recursively Load Directory Files Source: https://factory-muffin.thephpleague.com/api/files/Factory.html Iterates through a directory to include all PHP files found, typically used for loading factory definitions. ```php private function loadDirectory($path) { $directory = new RecursiveDirectoryIterator($path); $iterator = new RecursiveIteratorIterator($directory); $files = new RegexIterator($iterator, '/^.+\.php$/i'); foreach ($files as $file) { include $file->getPathName(); } } ``` -------------------------------- ### Generate Optional Image URL Source: https://factory-muffin.thephpleague.com/usage/generators Set the 'profile_pic' attribute to a random image URL of 400x400 dimensions. The 'optional' flag means the attribute may sometimes be null. ```php League\FactoryMuffin\Facade::define('MyModel', array( 'profile_pic' => 'optional:imageUrl|400;400', )); ``` -------------------------------- ### Call Static Model Methods with Arguments Source: https://factory-muffin.thephpleague.com/usage/generators Set the 'bar' attribute by calling a static method 'MyModel::anotherMethod()' with an argument 'hello'. ```php League\FactoryMuffin\Facade::define('MyModel', array( 'bar' => 'call|anotherMethod|hello', )); ``` -------------------------------- ### Method: generate() Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Generators.Base.html Generates and returns the attribute value based on the configured generator and options. The return type is mixed. ```php generate() : mixed ``` -------------------------------- ### PHP Method: generate() Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Generators.Factory.html Generates and returns data, which can be an integer or null. ```php generate() : integer|null ``` -------------------------------- ### PHP Property: $properties Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Generators.Factory.html An array defining the factory's properties. ```php $properties : array ``` -------------------------------- ### Retrieve Faker Instance Source: https://factory-muffin.thephpleague.com/api/files/Factory.html Returns the current Faker generator instance, initializing it with the configured locale if it does not exist. ```php public function getFaker() { if (!$this->faker) { $this->faker = Faker::create($this->fakerLocale); } return $this->faker; } ``` -------------------------------- ### Make Class Instance Source: https://factory-muffin.thephpleague.com/api/files/Factory.html The `makeClass` method instantiates a given class. It checks if the class exists and throws a `ModelNotFoundException` if it does not. It supports custom class makers. ```APIDOC ## POST /api/make-class ### Description Instantiates a given class. Throws an exception if the class does not exist. ### Method POST ### Endpoint /api/make-class ### Parameters #### Request Body - **class** (string) - Required - The name of the class to instantiate. ### Request Example ```json { "class": "App\Models\User" } ``` ### Response #### Success Response (200) - **instance** (object) - An instance of the specified class. #### Response Example ```json { "instance": { /* instance details */ } } ``` #### Error Response (404) - **error** (string) - Indicates that the model class was not found. #### Error Example ```json { "error": "ModelNotFoundException: Class App\Models\User not found." } ``` ``` -------------------------------- ### MethodNotFoundException Constructor Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.MethodNotFoundException.html Creates a new instance of MethodNotFoundException. It requires the model name, method name, and an optional custom message. ```php public function __construct(string $model, string $method, string|null $message = null): void ``` -------------------------------- ### Execute Static Method Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Generators.Call.html Invokes a static method on the model with the provided arguments. ```php execute(string $method, array $args) : mixed ``` -------------------------------- ### Define $factories property Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html The array of factories. ```php $factories : array ``` -------------------------------- ### Manage pending and saved objects Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Facade.html Methods to track, verify, and delete objects in the pending or saved state. ```php pending() : array ``` ```php isPending(object $object) : boolean ``` ```php saved() : array ``` ```php isSaved(object $object) : boolean ``` ```php isPendingOrSaved(object $object) : boolean ``` ```php deleteSaved() : \League\FactoryMuffin\Factory ``` -------------------------------- ### Method: detect() Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Generators.Base.html Detects the appropriate Generator class for a given attribute kind. It can optionally use a model instance and a Faker generator. ```php detect(string $kind, object|null $object = null, \Faker\Generator|null $faker = null) : \League\FactoryMuffin\Generators\Base ``` -------------------------------- ### Set custom maker Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html Set the custom maker closure. ```php setCustomMaker(\Closure $maker) : $this ``` -------------------------------- ### Add Factory Muffin to Composer Dependencies Source: https://factory-muffin.thephpleague.com/installing Add the league/factory-muffin package to your composer.json file under require-dev. Ensure you are using a compatible version, such as "~2.0". ```json { "require-dev": { "league/factory-muffin": "~2.0" } } ``` -------------------------------- ### POST /factory/seed Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Factory.html Generates multiple instances of a model and saves them to the database. ```APIDOC ## POST /factory/seed ### Description Generates a specified number of model instances and persists them to the database. ### Method POST ### Parameters #### Request Body - **times** (integer) - Required - The number of instances to create. - **model** (string) - Required - The model class name. - **attr** (array) - Optional - The model attributes. ### Response #### Success Response (200) - **seeds** (array) - An array of created model instances. ``` -------------------------------- ### SaveMethodNotFoundException Constructor Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.SaveMethodNotFoundException.html Creates a new instance of the SaveMethodNotFoundException. It requires the object, the method name, and an optional custom message. ```php function __construct(object $object, string $method, string|null $message = null): void ``` -------------------------------- ### NoDefinedFactoryException Constructor Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.NoDefinedFactoryException.html Creates a new instance of NoDefinedFactoryException. It requires the model name and an optional custom message. ```php public function __construct(string $model, string|null $message = null): void ``` -------------------------------- ### FactoryMuffin Model Operations Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Facade.html Methods for defining models, creating instances, and seeding data. ```APIDOC ## define(string $model, array $definition) ### Description Define a new model factory. ### Parameters - **model** (string) - Required - The model class name. - **definition** (array) - Optional - The attribute definitions. ### Response - **Returns** (\League\FactoryMuffin\Factory) - The factory instance. ## create(string $model, array $attr) ### Description Creates and saves an instance of the model in the database. ### Parameters - **model** (string) - Required - The model class name. - **attr** (array) - Optional - Attributes to override. ### Response - **Returns** (object) - The created model instance. ## seed(integer $times, string $model, array $attr) ### Description Returns multiple versions of an object. ### Parameters - **times** (integer) - Required - Number of instances to create. - **model** (string) - Required - The model class name. - **attr** (array) - Optional - Attributes to override. ### Response - **Returns** (array) - An array of created model instances. ``` -------------------------------- ### \League\FactoryMuffin\ExceptionsMethodNotFoundException Source: https://factory-muffin.thephpleague.com/api/classes/League.FactoryMuffin.Exceptions.MethodNotFoundException.html Details of the MethodNotFoundException class, including its constructor, properties, and getter methods. ```APIDOC ## \League\FactoryMuffin\ExceptionsMethodNotFoundException ### Description This exception is never directly thrown, but you may try to catch this exception rather than the 2 other exceptions that extend this class. ### Properties #### $model - **model** (string) - The model. #### $method - **method** (string) - The method. ### Methods #### __construct() - **model** (string) - Required - - **method** (string) - Required - - **message** (string|null) - Optional - #### getModel() Returns the model. #### getMethod() Returns the method. ```