Skip to content

Actions

Kyle Spraggs edited this page Jul 20, 2014 · 9 revisions

Actions

SpiffyFramework uses the concept of actions which was inspired by the Action Domain Response written by @pmjones. Actions are similar to the controllers in typical MVC except each action is a single class. The primary benefit of this pattern is each action only requires its own dependencies which reduces the size and complexity of your controller layer. This helps promote FAT models and SKINNY controllers or, in our case, actions.

Actions are invoked using SpiffyDispatch after a route connected to the action is matched. Defining actions are done while defining your routes so if you're here you've already defined actions!

Spiffy\Framework\Action\AbstractAction

Spiffy\Framework\Action\AbstractAction is an abstract class that contains sane defaults for your actions. It also includes several helper methods. It is recommended but not required that your actions extend this class.

Basic Action

namespace Application\Home;

use Spiffy\Framework\Action\AbstractAction;

class IndexAction extends AbstractAction
{
    public function __invoke()
    {
        return [];
    }
}

By default the __invoke() method is called to dispatch the action. The return value can be null, an array, a view model, or a response.

Returning a response short-circuits the rest of the event life-cycle and immediately returns the response content.

An action with dependencies

Most of the time your actions will interact with a service or some other piece of your application. In order to do this you must inject your dependencies. Below is an action using constructor injection.

namespace Application\Home;

use Spiffy\Framework\Action\AbstractAction;

class IndexAction extends AbstractAction
{
    /** @var MyService */
    private $service;

    public function __construct(MyService $service)
    {
        $this->service = $service;
    }

    public function __invoke()
    {
        return ['foo' => $this->service->getBar()];
    }
}

Read on to services to learn how to tell SpiffyFramework to inject the MyService dependency.