powered by Slim Framework
Follow @NesbittBrian rss

Updated ContextSensitiveLoginLogout example to Slim 2.x

Dec 6, 2012

A question, awhile back, on the Slim discussion forum asked how to create a login/logout workflow with a redirect to the originally requested page on login. I had created an example to show this using Slim 1.6.x. Recently I updated the example to work with the 2.x version of Slim. Lets review the changes that were applied to make this happen.

The example can be seen here https://github.com/briannesbitt/Slim-ContextSensitiveLoginLogout


The Slim 2.x branch added namespaces. This means we need to update our Slim references with the equivalent namespaced version. There are two ways we can do this. First lets see how it was done in our example. The following is the diff listing for our commit on the index.php file.

require 'vendor/autoload.php';

- $app = new Slim();
+ $app = new \Slim\Slim();

- $app->add(new Slim_Middleware_SessionCookie(array('secret' => 'myappsecret')));
+ $app->add(new \Slim\Middleware\SessionCookie(array('secret' => 'myappsecret')));

What you see above are the only code changes that were necessary to make this work with Slim 2.x. The other changes in the commit were to the readme and composer.json file.

The second method we could have implemented is to introduce the usage of the PHP keyword use. Importing the namespaces with the use keyword at the top of the file means we don't have to supply the full namespaced class when actually using and referencing the class. Lets see how that would have been done.

require 'vendor/autoload.php';

+ use Slim\Slim;
+ use Slim\Middleware\SessionCookie;

$app = new Slim();

- $app->add(new Slim_Middleware_SessionCookie(array('secret' => 'myappsecret')));
+ $app->add(new SessionCookie(array('secret' => 'myappsecret')));

Adding the use imports at the top prevents us from having to add \Slim\ in front of all of the Slim class references. Our example is simple so in this instance, I think either method is fine, but in a longer example you can see how using use might be the better option, however making the code less explicit.

This is a simple example so as we discussed the code changes were very minimal. You can refer to the following sites to see what else changed and further tips on upgrading:


Lazy loading Slim controllers using Pimple  Home This blog trimmed the fat - Now powered by Slim 2  
blog comments powered by Disqus