Download the PHP package zachleigh/yarak without Composer
On this page you can find all versions of the php package zachleigh/yarak. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download zachleigh/yarak
More information about zachleigh/yarak
Files in zachleigh/yarak
Package yarak
Short Description Laravel inspired devtools for Phalcon. Database migrations, model factories and database seeders.
License MIT
Homepage https://github.com/zachlegih/yarak
Informations about the package yarak
Yarak
yarak - (Falconry) a state of prime fitness in a falcon
Laravel inspired Phalcon devtools
- Database migrations that rollback step-by-step, reset the database, and refresh the database.
- Model factories for easy test data creation.
- Database seeders that fill your database with a single command.
- Create custom commands in minutes to streamline and personalize your workflow.
Contents
- Release Notes
- Install
- Database
- Generating Database Directories And Files
- Model Factories
- Defining Factories
- Using The Factory Helper
- Making Multiple Model Instances
- Overriding The Default Attributes
- Using Named Factories
- Model Relationships
- Database Seeding
- Creating Database Seeders
- Writing Database Seeders
- Using Database Seeders
- Migrations
- Generating Migrations
- Writing Migrations
- Creating Tables
- Updating Tables
- The Down Method
- Running Migrations
- Rolling Back Migrations
- Resetting The Database
- Refreshing The Database
- Custom Commands
- Generating Console Directories And Files
- Generating Custom Commands
- Writing Custom Commands
- Command Signature
- Defining Command Arguments
- Defining Command Options
- Accessing Command Arguments And Options
- Command Output
- Using Custom Commands
- Calling Yarak In Code
- Developing
- Credits and Contributing
Release Notes
Moving from 1.1. to 1.2.
The core command wrapper has been extracted to a separate package (zachleigh/artisanize). Where possible, Yarak classes have been maintained for the time being in order to minimize update issues. However, some interface type declarations may need to be updated after isntalling the new version.
Install
Requirements
This package assumes you have the following:
- Phalcon >= 3.0
- PHP >= 5.6.5
Install via composer
Register the service
Yarak requires the following config values in this structure:
Yarak uses your application's config so if your config is already structured this way, simply add the necessary values. If your config strategy differs from this, you have several options. First, you can create a specific Yarak config key and set all values there:
Then, when registering the service pass the config path:
If the config path is multiple levels deep, use dot notation:
If you wish to add config values when registering Yarak, pass them as an array and Yarak will merge them into your existing config:
Lastly, you can pass all config values when registering the service. Pass 'false' as the second parameter to the Kernel constructor to turn off config merging.
Create a yarak file
In the project root, create a file called yarak
. This file needs to do the following:
- Autoload all project files and vendor directory files
- Load the project services
- Resolve the Yarak kernel from the service container and call the
handle
method on it
Example:
The above example is included in the project at yarak/src/yarak_example. Copy it into your project with the following command, done from the project root:
Once the yarak file exists, make it executable:
Add the database directory to the composer autoloader
Because migrations do not follow psr-4 naming conventions, load them with a classmap.
You may have to dump the composer autoload cache for the change to take affect.
Test to make sure that it is working in the console:
Top
Database
Yarak gives users several helpful database functionalities that make development easier.
- Generating Database Directories And Files
- Model Factories
- Defining Factories
- Using The Factory Helper
- Making Multiple Model Instances
- Overriding The Default Attributes
- Using Named Factories
- Model Relationships
- Database Seeding
- Creating Database Seeders
- Writing Database Seeders
- Using Database Seeders
Generating Database Directories And Files
All database and migration functionalites require a standardized file hierarchy. To generate this hirearchy, use the db:generate
command:
This will create a database directory at the path set in the Yarak config. The database directory will contain migration, seeder, and factory directories and some file stubs to help you get started.
Model Factories
Model factories provide a simple way to create testing data using the Faker library.
Defining Factories
Model factories are located in the /database/factories
directory. This directory and a stub factory file can be created using the php yarak db:generate
command.
To define a factory, use the define
method on a variable called $factory
. The define
method has the following method signature:
The first argument is the full name/namespace of the class. The second argument is a callback that returns an array. This array must contain the data necessary to create the model. The third optional argument is a name for the factory. Setting the name allows you to define multiple factories for a single model.
To create a simple user model factory:
To create a named user model factory:
The ModelFactory class responsible for creating model instances extends Phalcon\Mvc\User\Component and has access to the DI and any services registered. To access the ModelFactory class, use the $factory
variable in the $attributes
closure.
Using The Factory Helper
Yarak comes with a global factory
helper function to make creating model instances simple. The factory function returns an instance of ModelFactoryBuilder which can be used to either make or create models. Calling make
on the returned class simply makes the model class, but does not persist the data in the database. Calling create
creates the class and persists it in the database.
Make a user model isntance, but don't persist it:
Create a user model and persist it:
Making Multiple Model Instances
If you require multiple instances of the model class, pass an integer as the second argument to factory
:
When more than one model is made, an array of models is returned.
Overriding The Default Attributes
To override the default attributes set in the factory definition, pass an array of overrides to make
or create
:
Using Named Factories
To use a name factory, pass the name as the second argument to the factory
function:
To make multiple instances of a named factory, pass the desired number of instances as the third argument:
Model Relationships
When making model instances that require model relationships to also be built, you have a couple options.
First, you can manually create related models. In this example, we have Posts and Users which have a one-to-many relationship: a post can only belong to one user but a user can have many posts. The posts table contains a users_id
column that references the id
column on the users table. Posts table migration:
First, we need to create factories for both users and posts:
To create three users with one post each, we could simply loop over newly created users and create a post for each, sending the user id as an attribute override:
For multiple posts, simply pass the desired number as the second variable to the factory helper:
Another way to create relationships is by using a closure returning a relationship in a factory definition:
Here we are using a factory within the factory to create a new user for each new post created. We are also naming the factory 'withUser' for convenience. To create 20 posts made by 20 users, we can simply do this:
Database Seeding
Database seeding gives you the ability to fill your database with testing data in a matter of seconds.
Creating Database Seeders
To create an empty database seeder file, use the make:seeder
command:
This will generate an empty seeder file in /database/seeds. It is recommended to create separate seeder files for individual database tables.
Writing Database Seeders
All database seeders must have a run
method where the database seeding logic is defined. In the run method, do whatever is necessary to fill the database table. Using model factories makes this process simple to acheive. An example seeder for a users tables might look like this:
Running this seeder will create five users in the database.
The parent Seeder class has a call
method that will call the run
method on other seeder files. This allows you to create several seeder files and then make a master DatabaseSeeder that will fill the entire database. We already have a UsersTableSeeder above, so let's now make a PostsTableSeeder:
This will create 5 posts for each of our users. We can then combine our two seeder files in a master DatabaseSeeder file:
This will run each seeder file in the order they are listed. First, we will create five users with the UsersTableSeeder, then for each of those users, we will create five posts with the PostsTableSeeder.
Using Database Seeders
To run database seeder files, use the db:seed
command:
The default seeder name is 'DatabaseSeeder'.
You may also use the --seed
flag with the migrate:refresh
command:
:exclamation:Refreshing the database will remove all data from your database. This command will drop all tables, run all the migrations again, then fill the database using the given seeder class name. The default value for the seeder name is 'DatabaseSeeder'.
Top
Migrations
Yarak migrations provide a simple, clean way to manage your database.
- Generating Migrations
- Writing Migrations
- Creating Tables
- Updating Tables
- The Down Method
- Running Migrations
- Rolling Back Migrations
- Resetting The Database
- Refreshing The Database
Generating Migrations
All migrations are stored in databaseDir/migrations. The databaseDir path may be set when registering the Yarak service.
To generate migrations, use the make:migration
command:
The migration name must be snake_case and will be used to create the migration file name and class name. For example:
Using the name create_users_table
will generate a migration class called CreateUsersTable
. Migration file names are generated using a timestamp and the given name. In this example, the generated file name might look something like this: 2017_03_04_055719_create_users_table.php.
If you are creating a new table, using the --create
flag plus the name of the database table will create a migration file with some additional boiler plate to save a little time.
Writing Migrations
Yarak uses Phalcon's Database Abstraction Layer to interact with the database. This guide will only cover the most common operations. For more detailed information about what is possible, please see the API Documentation. Because the official Phalcon migrations also use the database abstraction layer, the Phalcon migration documentation may also be useful.
Creating Tables
To create a table, use the $connection
variable's createTable
method.
To create a simple users table, your up
method might look something like this:
The definition array must contain a columns
array, and can also include indexes
, references
, and options
arrays. To define columns use Phalcon's DB Column class class, for indexes use the DB Index class, and for foreign keys use the DB Reference class.
For more information, see the official documentation.
Updating Tables
To modify a column, use the $connection
variable's modifyColumn
method:
Continuing the example above, our email column size is currently set to 20 which is clearly not big enough. To modify this, we can create a new migration:
In the created migration's up method, we can write the following:
Keep in mind that when using the Column class, type
is required.
To add additional columns to a table, use the addColumn
method:
So if we want to add an active
column to our users table, we create a new migration:
And our migration up method could look like this:
The official documentation contains some additional examples and information which may be helpful.
The Down Method
In order for migraion rollbacks to work, migrations must contain a down
method where the process described in the up
method is reversed. To continue our above example, when creating the users table, our down method would use the dropTable
method:
When modifying the email column, we could simply modify the column so that it returns to it's previous state:
When adding the active
column, use the dropColumn
method:
Running Migrations
To run all pending migrations, simply use the Yarak migrate
command:
This will run all migrations that have not yet been run. Migrations that are run at the same time will be in the same 'batch' and will be rolled back together.
Rolling Back Migrations
:exclamation:Before rolling back, be aware that all data in the tables you rollback will be lost.
To rollback the last batch of migrations, call migrate:rollback
:
Use migrate:rollback
with the optional --steps
flag to rollback more than one batch.
This will rollback the last two batches of migrations.
Resetting The Database
Using the migrate:reset
command will rollback all migrations.
:exclamation:Resetting the database will remove all data from your database. Be sure any data you wish to keep is backed up before proceeding.
Refreshing The Database
Refreshing the database will rollback all migrations and then re-run them all in a single batch.
:exclamation:Refreshing the database will remove all data from your database. Be sure any data you wish to keep is backed up before proceeding.
When using the migrate:refresh
command, you may also use the --seed
flag to run all your Using Database Seeders for more information.
Top
Custom Commands
Yarak can also be extended and used as a general command line task runner.
- Generating Console Directories And Files
- Generating Custom Commands
- Writing Custom Commands
- Command Signature
- Defining Command Arguments
- Defining Command Options
- Accessing Command Arguments And Options
- Command Output
- Command Signature
- Using Custom Commands
Generating Console Directories And Files
To generate all the directories and files necessary for the console component to work, use the console:generate
command:
This will create a console directory, a commands directory, an example command, and a Kernel.php file where you can register your custom commands. If the config value namespaces => root
is set, Yarak will use file path information and the set root namespace to automatically generate namespaces. If you use a non-standard namespace, set namespaces => console
as shown below.
Generating Custom Commands
Before generating a custom command, be sure to include consoleDir
in your config. You may also register a console namespace if the automatically generated namespaces are incorrect. By default, custom commands with be in the defined console directory in a folder called commands
. You can override this by registering a commandsDir
.
Do not forget to register your console namespaces with the Phalcon loader.
Once consoleDir
is registered, use the make:command
command to generate a custom command stub.
Writing Custom Commands
A command class has three components: a signature, a description, and a handle method.
signature
is where you define your command's name, arguments, and options. This is discussed in detail below. description
is where you can set a description message for your command to be displayed when using the console. The handle
method will be called when the command is fired and is where you should write the logic for your command. It may be useful to extract the bulk of your logic to a separate service class.
Command Signature
The command signature is written in the same way that the command will be used in the console and consists of three parts: the command name, arguments, and options. The command name must come first in the signature and can be namespaced by prefixing the command name with a namespace followed by a colon (':'):
Arguments and options are enclosed in curly braces and follow the command name. Options are prefixed by two dashes ('--').
Defining Command Arguments
A standard argument consists of the argument name wrapped in curly braces:
The argument name, arg
in the example above, is used to access the argument value via the argument
method.
To make an argument optional, append a question mark ('?') to the argument name:
To give the argument a default value, separate the argument name and the default value with an equals sign ('='):
If no value is provided for the argument, the default value will be used.
If the argument is in array form, append an asterisk ('*') to the argument name:
Arguments can then be passed to the command by space separating them:
This will set the value of arg
to ['one', 'two', 'three']
.
Argument arrays can also be set as optional:
When accessing optional argument arrays, arguments that have not been passed equal an empty array.
It is often helpful to provide a description with an argument. To do this, add a colon (':') after the argument definition and append the description:
Defining Command Options
A standard option consists of the option, prefixed by two dashes ('--'), wrapped in curly braces:
The option name, opt
, is used to access the argument value via the option
method. Standard options do not take values and act as true/false flags: the presence of the option when the command is called sets its value to true and if it is not present, the value is false.
To define an option with a required value, append an equals sign ('=') to the option name:
To set a default value, place it after the equals sign:
Options may also have shortcuts to make them easier to remember and use. To set a shortcut, prepend it to the command name and separate the two with a pipe ('|'):
Now, the option may be called inthe standard way:
Or by using the shortcut:
Options may also be passed as arrays:
When passing options arrays, each value must be prefixed by the option name:
The value of opt
will be set to ['one', 'two', 'three']
.
Just like with arguments, the option description can best by appending a colon (':') and the description to the option name definiton:
Accessing Command Arguments And Options
To access arguments in the handle method, use the argument
method:. If an argument name is given, it will return the value of the argument and if nothing is passed, it will return an array of all arguments:
The option
method works in the exact same way:
There are also hasArgument
and hasOption
methods on the command object:
Asking for confirmation
The confirm
method can be used to ask the user for a simple confirmation
Ask a question
In case an open question needs to be prompted the user, the ask
method can be used.
The second argument provides a default fallback
Ask for a password
The user answer can be hidden by using the askPassword
method
Choosing from a list
The choose
method only allows an answer from a predefined list of choices
Auto-completion
The anticipate
method can provide the user some auto-completion help when starting to write.
The user can still choose any answer, regardless of the auto-completion hints
Multi choice
When the user should be allowed to choose more than a single answer, the choice
method allows to select them from a list
Command Output
Every command has an output
variable stored on the object that has several methods to help write output to the console.
The write
method outputs plain unformatted text, writeInfo
outputs green text, writeError
outputs red text, and writeComment
outputs yellow text:
The output variable is a simple wrapper around Symfony's output class. To access this class, use the getOutputInterface
method:
Keep in mind that the Yarak command class simply wraps up the Symfony console component. All Symfony command features are available on your custom command object. See the Symfony console component documentation for more details.
Using Custom Commands
Before using your custom command, you must register it in the command Kernel $commands
array:
Onces registered, the commands may be used like any other Yarak command:
Top
Calling Yarak In Code
To call a Yarak command from your codebase, use the Yarak::call static method.
For example, to call migrate:rollback --steps=2
:
Yarak will use the default DI to get its settings. If the resolved default DI is not working, pass an instance of Phalcon\Di as the third argument to the call method:
If you are running PHP 5.6 or lower, using the static call method may result in the following error message:
To avoid this error, pass the $di as the third variable to Yarak::call as shown above.
Top
Developing
To set up the project locally for development, clone the repo and run composer install
from the project root directory. Create the necessary database and enter your database configuration details in both codeception.yml
and app/config/config.php
. Run the full test suite with php vendor/codeception/codeception/codecept run
or use the following composer scripts:
composer test
: run the full test suitecomposer testf
: run only the functional testscomposer testu
: run only the unit tests
Top
Credits and Contributing
This project is largely inspired by the Laravel project. Some portions of code in Yarak were taken directly from the Laravel project. Many thanks to @taylorotwell and the rest of the Laravel contributors.
Contributions are more than welcome. Fork, improve and make a pull request. For bugs, ideas for improvement or other, please create an issue.
All versions of yarak with dependencies
vlucas/phpdotenv Version ^2.4
symfony/filesystem Version ^3.2
phalcon/zephir Version ^0.9.6
fzaninotto/faker Version ^1.6
zachleigh/artisanize Version ^1.0