If you are a PHP developer for some time now, then you already heard about Slim framework. Slim is mainly popular for building APIs. Reason is its routing feature but you can also develop dynamic websites and systems using slim.
As per official definition:
Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.
Features of Slim Framework:
There are four main features of slim.
- HTTP Router: Slim provides a fast and powerful router that maps route callbacks to specific HTTP request methods and URIs. It supports parameters and pattern matching.
- Middleware: Build your application with concentric middleware to tweak the HTTP request and response objects around your Slim app
- PSR-7 Support: Slim supports any PSR-7 HTTP message implementation so you may inspect and manipulate HTTP message method, status, URI, headers, cookies, and body
- Dependency Injection: Slim supports dependency injection so you have complete control of your external tools. Use any Container-Interop container.
I am not going to cover API in this tutorial. I will do that in my upcoming tutorials. But right now I am going to develop a website using slim 3 framework.
This will be the series of tutorials because I cannot cover all in one tutorial. But I can share you what I will going to do in this tutorial.
Slim 3 Framework Tutorial:
- Download Slim 3 via composer
- Add PHP-View via composer for templating. Because slim does not have a view layer
- Create Src folder and put routes and settings there.
- Create index.php on folder root.
- Create Templates folder and put homepage, about, 404 and layouts structure.
- Create Assets folder and put all css and js there.
If you don’t have composer on your machine. Then you can check my post How to install Composer on Windows with XAMPP.
I am using xampp for my local development so I am going to create folder in htdocs
as slimnew
. Now open command prompt (ctrl +r and type cmd) go to slimnew
folder under htdocs
and type below command.
1 |
Composer require slim/slim "^3.0" |
When you hit enter then slim installation will start and you will see below messages.
Slim 3 initial Folder Structure:
By default installation create only vendor
folder and composer .json
and composer.lock
file. Just like below
Download Views and Templates:
Slim does not have a view layer by default because slim view is the http response. But slim provides the Twig-View and PHP-View components to render templates.
I am going to use PHP-View for templating. Type below command under htdocs/slimnew
1 |
composer require slim/php-view |
Create Src Folder:
Create Settings.php:
Now create src
folder under slimnew
and create file settings.php
and put below code in settings.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php return [ 'settings' => [ 'displayErrorDetails' => true, // set to true in production 'addContentLengthHeader' => false, 'db' =>[ 'host'=> 'localhost', 'user'=> 'root', 'password'=> '', 'dbname'=> 'demo', ] ], ]; |
Above code is just an array with settings
index as first and displayErrorDetails
, addContentLengthHeader
and db indexes as second with their respective values. I will cover database in my next tutorial.
Create routes.php
Slim provides 8 routes for handling HTTP request. We will cover them according to the requirement of this tutorial. But if you want to look them. You can visit Slim Router.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php use Slim\Http\Request; use Slim\Http\Response; // Routes $app->get('/', function (Request $request, Response $response, array $args) { $data = array( "main_heading"=>"Welcome to Slim 3 framework for Beginner", "sub_heading" => "In this tutorial we are going to learn slim 3 framework" ); return $this->view->render($response, 'homepage.php',$data); }); $app->get('/about',function(Request $request, Response $response, array $args) { $data = array( "main_heading"=>"About Us", "sub_heading" => "In this tutorial we are going to learn slim 3 framework" ); return $this->view->render($response, 'about.php',$data); }); |
In the above routes.php
code:
$app->get()
: handles only GET HTTP request and it takes 2 arguments. The route pattern and the route callback.- First
$app->get
has only take “/” so this means this route is for home page. $data is an array having main_heading and sub_heading keys. $this->view->render
: has 3 parameters one is$repsonse
, second is template and third is argument pass in template file.- Second
$app->get
takes “/about” which means ifslimnew/about
will land on this route. Homepage.php
andabout.php
pages will be placed in templates folder.
Create index.php
Create index.php
on folder root htdocs/slimnew/index.php
. Paste below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?php use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; require('vendor/autoload.php'); $settings = require __DIR__ . '/src/settings.php'; $app = new \Slim\App($settings); // Get container $container = $app->getContainer(); // Register component on container $container['view'] = function ($container) { return new \Slim\Views\PhpRenderer('templates',['baseUrl' => '/slimnew/']); }; $container['notFoundHandler'] = function ($c) { return function ($request, $response) use ($c) { return $c['view']->render($response->withStatus(404), '404.php', [ "myError" => "Error" ]); }; }; // Register routes require __DIR__ . '/src/routes.php'; $app->run(); ?> |
In the above of index.php
on top we used:
Use \Psr\Http\Message\ServerRequestInterface as Request
: Object has all the server parameter.Use \Psr\Http\Message\ResponseInterface as Response
: Object has response status, headers and content typerequire('vendor/autoload.php')
: is loading all slim libararies$settings = require __DIR__ . '/src/settings.php'
: just include settings.$app = new \Slim\App($settings)
: pass settings array in $app object.$container = $app->getContainer()
: get slim container.$container['view']
: register PHP-View as a view container which will render layout of templates folder.$container['notFoundHandler']
: is used to register 404 page.require __DIR__ . '/src/routes.php'
: include route file for website routing.$app->run()
: run slim app.
Create Templates Folder:
Homepage.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php include('layouts/header.php');?> <header class="bg-primary text-white"> <div class="container text-center"> <h1><?php echo $main_heading?></h1> <p class="lead"><?php echo $sub_heading?></p> </div> </header> <section id="about"> <div class="container"> <div class="row"> <div class="col-lg-8 mx-auto"> <h2>Slim 3 framework</h2> <p class="lead">Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem IpsumLorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum</p> </div> </div> </div> </section> <?php include('layouts/footer.php');?> |
In the above code we print $main_heading
as main heading and $sub_heading
as paragraph. Both $main_heading
and $sub_heading
are passed as an argument in src/routes.php
file.
About.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php include('layouts/header.php');?> <header class="bg-primary text-white"> <div class="container text-center"> <h1><?php echo $main_heading?></h1> <p class="lead"><?php echo $sub_heading?></p> </div> </header> <section id="about"> <div class="container"> <div class="row"> <div class="col-lg-8 mx-auto"> <h2>About Slim 3 framework</h2> <p class="lead">Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem IpsumLorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum</p> </div> </div> </div> </section> <?php include('layouts/footer.php');?> |
Create layouts folder:
In templates/layouts
folder create 2 files header.php
and footer.php
header.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Slim 3 Framework </title> <!-- Bootstrap core CSS --> <link href="<?= $baseUrl; ?>assets/js/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="<?= $baseUrl; ?>assets/css/scrolling-nav.css" rel="stylesheet"> </head> <body id="page-top"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="<?= $baseUrl; ?>">Slim 3 Framework</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="<?= $baseUrl; ?>">Home</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="index.php/about">About</a> </li> </ul> </div> </div> </nav> |
Above is the header code which include css files and render top navigation. $baseUrl
is a variable which we set in index.php
in view container.
footer.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<!-- Footer --> <footer class="py-5 bg-dark"> <div class="container"> <p class="m-0 text-center text-white">Copyright © Your Website 2017</p> </div> <!-- /.container --> </footer> <!-- Bootstrap core JavaScript --> <script src="<?= $baseUrl; ?>assets/jsz/jquery/jquery.min.js"></script> <script src="<?= $baseUrl; ?>assets/js/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Plugin JavaScript --> <script src="<?= $baseUrl; ?>assets/js/jquery-easing/jquery.easing.min.js"></script> <!-- Custom JavaScript for this theme --> <script src="<?= $baseUrl; ?>assets/js/scrolling-nav.js"></script> </body> </html> |
Assets Folder:
In this folder we put js and css files.
Final Slimnew Folder Structure:
All things are done now it’s time to check slimnew in browser. We have 2 options for open site in browser first one is goto browser and type slimnew url (for me it is localhost:8080/slimnew
) and second method is goto command prompt xampp/htdocs/slimnew
and type php -S localhost:9000
and then goto browser and type localhost:9000
.
If you are using second option then must change baseUrl in index.php
right now it is set to /slimnew/
you have to change this with "/"
.
Second tutorial on this series is Slim 3 Framework Tutorial: Create, Configure, Load and Access Database
I’ve just started learning Slim Framework and i’ve found you’r way is the simplest one. Great Job. If by any chance you’ve integrated with database as well please let me know. Thank you so much
Thank you Vipul 🙂 .. Below is the database integration link you can check.
https://www.wdb24.com/slim-3-framework-tutorial-create-configure-load-and-access-database/
Hi – Sorry for my english
in About(page) get this: http://localhost/slimnew/index.php/index.php/about
2 times index.php…after i made clic in About(menu) and get Error 404