Controller Patterns in Slim 3

I would suggest that you give a quick read on http://glenneggleton.com/page/slim-3-controllers-and-actions as this article will build on some of the previous stuff there.

Route Actions

A route action is essentially the 2nd argument in the http verb method inside slim.

$app->get('/hello', /*Route Action*/ function ($req, $res, $args) {});

//Previous Article
$app->get('/hello', /*Route Action*/ MyAction::class); //MyAction defines __invoke($req, $args)

//Other Options

//Option A
$app->get('/hello', /*Route Action*/ [MyAction::class, 'myAction']); //MyAction defines myAction($req, $args)


//Option B
$app->get('/hello', /*Route Action*/ MyAction::class . ':myAction'); //MyAction defines myAction($req, $args)

Option A

This works because inside Slim we use the call_user_func_array() method to invoke the route action, and as such the array will return true to is_callable() and Slim will execute that.

Option B

This works because we have added this regex into our dispatcher. It is probably a bit slower than option A however I think it's more or less just a style thing. I don't have any reasons to use A over B. I typically use Option A if I have controller classes instead of action classes.

Conclusion

As with most things in programming there are many different ways to accomplish a goal. Be consisent in the strategy that you use and everybody will be happy!

Written by Glenn Eggleton on Wednesday October 4, 2017
Permalink - Chapter: Slim