CakePHP 3 the Way to Reach Controller Invoking part 2 of 3


This is a continued article from CakePHP 3 the Way to Reach Controller Invoking part 1 of 3.

index.php remains the following 5 lines.

Let’s see DispatcherFactory::create().

DispatcherFactory::create()

create method creates an instance of Dispatcher class, CoreRoutingDispatcher. This is ordinal use of factory pattern. Dispathcer class doesn’t have any special constructing process, constructor isn’t written, so create method simply create an instance.

And with foreach, addFilter method adds each filter pushed in static::$_stack. Here, the filters we saw in CakePHP 3 the Way to Reach Controller Invoking part 2 of 3 will be added.

Let’s look into addFilter.

addFilter

$this->eventManager() executed in addFilter doesn’t defined in Dispatcher.php, it’s defined in EventManagerTrait that Dispatcher uses.

eventManager

eventManager() method returns $this->>_eventManager, the instance of EventManager.

Now back to addFilter, at on method filters are added as event listeners.

on

Instance of filter is passed as argument to on method. All filters we discussing about inherit DispatcherFilter. And DispatcherFilter implements EventListenerInterface, so the first if clause is processed and _attachSubscriber is executed and the process ends.

Now, look into _attachSubscriber.

_attachSubscriber

It configures callbacks.

In this method, gather callbacks callbacks, that should be configured, with implementedMethod and call $this->on($eventKey, $options, $method) with them.

implementedMethod doesn’t defined in each filter, it’s defined in the parent class of each filter, DispatcherFilter.

implementedEvents

Back to _attachSubscriber, the first if clause will be executed and it calls _extractCallable.

Then, look into _extractCallable.

_extractCallable

Argument $function will be assigned an array, $object will be assigned $subscriber which is instance of filter, $method will be assigned 'handle', $options will be assigned an associative array. Let’s look at the next process. I will research handle method when it’s required.

The code like on('Dispatcher.beforeDispatch', ['priority' => 10], [FilterObject, 'handle']); will be executed. Array of object and its method is added to _listener associative array with key of event and priority.

After this event listener registration, it starts processing request.

Continued to CakePHP 3 the Way to Reach Controller Invoking part 3 of 3.