Lessons: 2Length: 11 minutes

Next lesson playing in 5 seconds

  • Overview
  • Transcript

1.2 First Look at Slim PHP

In this lesson, I’ll show you the basics of Slim PHP for micro web apps. You’ll get an understanding of how a typical Slim application is constructed, specifically how to build and configure routes, retrieve GET and POST data, and assign and output template variables.

Code Snippet

The following snippet creates a route to render the index.phtml template. The name parameter in the URL will be passed to the template in the $args array.

$app->get('/[{name}]', function ($request, $response, $args) {
  return $this->render($response, 'index.phtml', $args);

Related Links

1.First Look at Slim PHP
2 lessons, 10:47


First Look at Slim PHP

1.2 First Look at Slim PHP

[SOUND] I'm Matthew Setter for Tuts+ and welcome to the introductory coffee break course on Slim PHP. Specifically, version three. In this short seven to 12 minute course, I'm going to step you through how to use Slim to create a basic micro application. You're going to get an understanding of how a typical Slim application is constructed, specifically how to build and configure routes, retrieve GET & POST data, and assign and output template variables. To follow along, you're only gonna need a few things. These are PHP 5.6 or 7.0 ideally, Composer and Git. There's loads more that you could use but I don't wanna throw too much at you in such a short period of time. If you came to know more though, tweet me @settermjd on Twitter. In your terminal run the command composer create-project slim/slim-skeleton slim-project. This last a bit of a mouthful to say or create a new project directory called Slim-project and in there install a basic slim project. When the install is finished running if we have a look at what's been generated, we can see that it's created quite an intuitive directory structure. There's a log directory file system logs. The standard public directory which is the document route, a source directory for source files, templates for view template files, a test directory for test classes, and it's included the external dependencies in the composer standard vendor directory. Looking in composer.Json, you can see the requirements PHP version 5.5 or greater Slim, slim PHP view and and monologue. Nice and light just the way you'd like it when you're creating a micro application. It's also included PHP unit as a development dependency and created a PS our full source and test namespace, so that we can begin creating class files straight away when we come to do so along with some handy scripts. Looking in public slash index not PHP we can see that it's created a handy bootstrap file which creates a slim application object, configuring it with the settings from settings.PHP, which is located in the source directory. We'll have a look at that in just a moment. It then loads the dependencies, middleware and routes before booting the application by calling the app object run method. Before we dig into the other configuration file so let's boot the application and have a quick look at what it generates. From the terminal I'll call composer start which launches the application using PHP's inbuilt web server. And makes it available on port eighty eighty on a local host. Viewing it in the browser it's nothing too special let's be fair. Just one route but it does work. Now let's look at the other configuration files. In settings you can see that era logging is enabled that it sets the template directory passed to the templates directory. And provides the logon configuration setting the log file path and default logging level to debug. Next let's have a look at the applications dependencies. Configured via src/dependencies of PHP. You can see that it sets up two dependencies. These are renderer and logger. Render is a PHP render object which uses templates to render HTML output. Logger is an instance of a monologue logger object which uses the logger settings which we just saw resulting in writing logs to the local file system. Looking in src/middleware.php, none middleware is created by default. And I'm not covering middleware in this course. I don't want to overwhelm you with too much information in such a relatively short period of time but it will be covered in a future coffee break course. So stay tuned for more on that in the future. Finally looking in src/routes.php, we can see that one route has been created. This basics playing in the little bit of detail by calling the get method, a route is created which will only be accessible by a get request. Using any other method will result in a 404 not found response. The first argument is the route to match. In this case it matches the application's URI with no path or query parameters. It also accepts one optional argument called name. The optional status is indicated by the enclosing parentheses. The second argument is the handler, in this case, a callback. To the callback, I pass the applications request and response objects. Which always the case with Slim, along with optional arguments. The handler first retrace the logger service from the DR container and logs a message at the information level that the default route's been rendered. It then renders index.phtml. Located in the templates directory. Now with all that said let's have a look at the contents of index stop of phtml so that you can see how templates work. Here in the file you can see that it's an HTML PHP file combination. If a name has been supplied then it renders the value of nine which is being set as a local variable. Otherwise it renders try SlimFramework. Nice bit of advertising when you say. Now let's look at how template variables are supplied. Notice here in Rostock PHP that there's no explicit passing of name to the template. This is a bit of magic I like to think on Slim's part. It's done implicitly if it's said. Now just while we're looking at this. Don't worry if you feel you've missed something there. I know that I thought I had the first time. However, and given that, we could be a bit more explicit by calling the request objects get attribute method. Like so, assigning it to a new element called name in the args array. Well, is not strictly necessary it's less likely I feel to cause confusion for anybody reading the code including yourself. And that is the kind of code that I like. Now let's add a second template and variable and this I'm calling time. I'll do that after the assignment of name setting its value with PHP's time function. With that done, now it's gone printed out in the template. As before we can use PHP short error syntax to save us time and effort. However, I like to be that much more explicit and use a print statement instead. Switching back to the browser and reloading the page, we can now see that the two variables are printed out on the default route. Okay, now that we've gotten the basics in place, let's start building on what we've learned by learning how to create post routes and extract post data. To do so let's first add a post route called add. We can do so by calling the post method similar to how we called the get method previously. We could also call the map method and pass in a list of the http methods which this route will accept like so. In this case just post. With that done, we can make use of two methods on the request object to retrieve information posted to the route. These are getParsedBody() and getParsedBodyParam(). GetParsedBody() returned an associative array of all POST parameters. GetParsedBodyParam(), as you may suspect, returns the value of a specific parameter. Optionally, supplying a default value, if the value that we're looking for hasn't been set. Quite handy by the way to avoid template errors. Now depending on whether you need all post data or just one specific value, these methods coming in very handy. This is because they perform background checks to determine if a value is present in the post super global before attempting to retrieve it. Whereas avoiding errors and saving us in time. However, one thing I need to stress is that they don't perform any form of data sanitization. So don't think that just by using them, your user input is now safe. With that said on their create a new template which prints out the value of name. And with that done we now need to test the code. To do that logically we can do it in the browser. So I'm going to make use of postman. If you've not heard of postman it's an excellent tool for testing APIs or in our case simply making post requests. Here in my copy of postman, I'll answer the URL of your test site and set the method to be post. After the battle click body so that I can add some post added to the request adding a key of name, and the value of Mathew. With that done, I click Send. And when the response is returned, you can see that my name is returned as the sole contents of the response body and that is a rapid overview of Slim PHP Version three. We've seen how basic application is composed along with an overview of how routes work, how to assign template variables and how to retrieve data from GET & POST requests. I hope. I truly do. Now that it showed you just how easy just how straightforward and efficient it can be to create micro applications using SLIM as well as await your appetite for future coffee bread courses on SLIM PHP by yours truly.

Back to the top