Download the PHP package sarfraznawaz2005/actions without Composer
On this page you can find all versions of the php package sarfraznawaz2005/actions. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download sarfraznawaz2005/actions
More information about sarfraznawaz2005/actions
Files in sarfraznawaz2005/actions
Package actions
Short Description Laravel package as alternative to single action controllers with support for web and api in single class.
License MIT
Informations about the package actions
[![Latest Version on Packagist][ico-version]][link-packagist] [![Total Downloads][ico-downloads]][link-downloads]
Laravel Actions
Laravel package as an alternative to single action controllers with support for web/html and api in single class. You can use single class called Action to send appropriate web or api response automatically. It also provides easy way to validate request data.
Under the hood, action classes are normal Laravel controllers but with single public __invoke
method. This means you can do anything that you do with controllers normally like calling $this->middleware('foo')
or anything else.
Table of Contents
- Why
- Requirements
- Installation
- Example Action Class
- Usage
- Send Web or API Response Automatically
- Validation
- Utility Methods and Properties
- Creating Actions
- Registering Routes
- Bonus: Creating Plain Classes
Why
- Helps follow single responsibility principle (SRP)
- Helps keep controllers and models skinny
- Small dedicated class makes the code easier to test
- Helps avoid code duplication eg different classes for web and api
- Action classes can be callable from multiple places in your app
- Small dedicated classes really pay off in complex apps
- Expressive routes registration like
Route::get('/', HomeAction::class)
- Allows decorator pattern
Requirements
- PHP >= 7
- Laravel 5, 6
Installation
Install via composer
That's it.
Example Action Class
``
In __invoke()
method, you write actual logic of the action. Actions are invokable classes that use __invoke
magic function turning them into a Callable
which allows them to be called as function.
Usage
As Controller Actions
Primary usage of action classes is mapping them to routes so they are called automatically when visiting those routes:
``
Note that the initial
\
here is important to ensure the namespace does not become\App\Http\Controller\App\Http\Actions\PublishPostAction
As Callable Classes
``
Send Web or API Response Automatically
If you need to serve both web and api responses from same/single action class, you need to define html()
and json()
method in your action class:
``
With these two methods present, the package will automatically send appropriate response. Browsers will receive output from html()
method and other devices will receive output from json()
method.
Under the hood, we check if Accept: application/json
header is present in request and if so it sends output from your json()
method otherwise from html()
method.
You can change this api/json detection mechanism by implementing isApi()
method, it must return boolean
value:
``
Using Action Classes for API Requests Only
Simply return true
from isApi
method and use json
method.
Using Action Classes for Web/Browser Requests Only
This is default behaviour, you can simply return your HTML/blade views from within __invoke
or html
method if you use it.
Validation
You can perform input validation for your store
and update
methods, simply use protected $rules = []
property in your action class:
``
In this case, validation will be performed before __invoke
method is called and if it fails, you will be automatically redirected back to previous form page with $errors
filled with validation errors.
Tip: Because validation is performed before
__invoke
method is called, usingrequest()->all()
will always give you valid data in__invoke
method which is why it's used in above example.
Custom Validation Messages
To implement custom validation error messages for your rules, simply use protected $messages = []
property.
Ignoring/Filtering Request Data
If you want to remove some request data before it is validated/persisted, you can use the protected $ignored = ['id'];
. In this case, id
will be removed from the request eg in other words it will be as if it was not posted in the request.
Utility Methods and Properties
Consider following action which is supposed to save todo/task into database and send appropriate response to web and api:
``
There are few things to notice above that package provides out of the box:
- Inside
__invoke
method, we used$this->create
method as shorthand/quick way to create a new todo record. Similarly,$this->update
and$this->delete
methods can also be used. They all returnboolean
value. They all also accept optional callback:
``
Using these utility methods is not required though.
-
If you return something from
__invoke
method, it can be read later fromhtml
andjson
methods as first parameter. In this case, boolean result of todo creation (return $this->create($todo)
) was used in bothhtml
andjson
methods via$result
variable whos name can be anything. -
Any validation errors are saved in
$this->errors
variable which can be used as needed. - In
html()
method, we have usedself::MESSAGE_CREATE
which comes from parent action class. Similar,self::MESSAGE_UPDATE
,self::MESSAGE_DELETE
andself::MESSAGE_FAIL
can also be used.
Tip: You can choose to not use any utility methods/properties/validations offered by this package which is completely fine. Remember, action classes are normal Laravel controllers you can use however you like.
Transforming Request Data
If you want to transform request data before validation is performed and before __invoke()
method is called, you can define transform
method in your action class which must return an array:
bash php artisan make:action ShowPost bash php artisan make:action Post --resource bash php artisan make:action Post --api bash php artisan make:action Post --actions=show,destroy,approve bash php artisan make:action Post --resource --except=index,show,edit bash php artisan make:action Post --resource --namespace=Post bash php artisan make:action ActivateUser --namespace=\App\Foo\Bar bash php artisan make:action EditPost --force bash php artisan make:class FooBar
`FooBar` class will be created under `app/Actions` folder:
``
Note that these are plain old PHP classes you can use for any purpose. *Ideally*, they should not be dependent on Laravel framework or any other framework and should have single public method as api such as `execute` and any more private/protected methods needed for that class to work. This will allow you to use them across different projects and frameworks. You can also think of them as service classes.
## Credits
- [Sarfraz Ahmed][link-author]
- [All Contributors][link-contributors]
## License
Please see the [license file](license.md) for more information.
[ico-version]: https://img.shields.io/packagist/v/sarfraznawaz2005/actions.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/sarfraznawaz2005/actions.svg?style=flat-square
[link-packagist]: https://packagist.org/packages/sarfraznawaz2005/actions
[link-downloads]: https://packagist.org/packages/sarfraznawaz2005/actions
[link-author]: https://github.com/sarfraznawaz2005
[link-contributors]: https://github.com/sarfraznawaz2005/actions/graphs/contributors