3 years ago by: matt

Edit: I have since this article was written updated the Phalcon documentation here to include this example. I have also put in a pull request to 2.1.x to put this functionality into the dispatcher in the phalcon core.

So this is something I discovered today after creating a new feature request over on the cphalcon GitHub. My initial request was to allow for route model binding similar to what is available in Laravel 5.

In Laravel 5 we can do the following:

Route::get('api/users/{user}', 'Controller@action);

Which then allows the "user" model if it exists to automatically be injected into the action if we use:

public function action(User $user)
    //access to normal user object

Phalcon PHP Route Model Binding

Turns out we already had this all along. The documentation just had it hidden away as routing "conversors"

So we can actually get the same result in Phalcon PHP using the "convert" method on the route we are adding.

Where we define our routes:

$router->add('/user/{user}', [
    'controller' => 'user',
    'action' => 'show',
])->convert('user', function ($id) {
    return User::findFirst($id);

Now within our "user" controller the show method can accept a User model in the declaration and it will be passed in based on the result from the convert transformation.

public function showAction(User $user)
   //User object loaded already

And there you have it. Route model binding in Phalcon PHP. I will push an update to include this example in the documentation as its not as straightforward to find as I thought it would have been. 

Some things to do next would be to look into instead of doing a "findFirst()" it would be nice to have a "findOrFail()" which in the case of a row not existing in the database it will forward to a 404 or something, but that's for another day.