How to create pages in PHP Slim 3 project

How to create routes and views in PHP Slim 3 project

Posted by Margie Crona on October 28, 2021

How to create pages in PHP Slim 3 project

How to create routes and views in PHP Slim 3 project

Posted by Margie Crona on October 28, 2021

In this tutorial you will be shown how to set up the PHP slim 3 framework with routes and views. Slim is mainly used for API building because it is lightweight with all the capabilities to create secure routing. 

Before we begin the lesson make sure you have composer and a development stack such as Xampp installed on your machine. If you do not have composer stack installed and you have windows 10 you can go here https://wecode101.com/install-composer-on-windows-10 to learn how.

For this tutorial, I will be using Xampp as the development platform. However, you can still follow along if you use a different stack; the process is very similar.

Step 1. Go to the htdocs folder in your Xampp directory and create a folder slim.

path to Xampp directory C:\xampp\htdocs

Step 2. Use command prompt to cd in slim folder and create a composer.json file

path to slim folder C:\xampp\htdocs\slim

Step 3. Edit composer.json by placin 2 curly brace

{}

Step 4. Execute command within slim folder

Composer require slim/slim "^3.0" 

A vendor folder should be created by running the command and you should see changes in composer.json file.

Step 5. Execute command within slim folder to get the view templates to be rendered

Composer require slim/php-view

Now you have the basic Slim components to start setting up your project.

Step 6. Create an app folder within the root of the slim directory

Step 7. Create a file settings.php within the app folder and add script below

<?php
return [
    'settings' => [
        'displayErrorDetails' => true, // this would normally be set to false in production
        'addContentLengthHeader' => false,
       
      'db' =>[
                'host'=> 'localhost',
                'user'=> 'root',
                'password'=> '',
                'dbname'=> 'test',
            ]  
       
    ],
];

Step 8. Create another file routes.php within the app folder and add script below

<?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",
    "sub_heading" => "In this tutorial we are going to learn how to install webpack to the slim 3 framework "
    );
    return $this->view->render($response, 'home.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 installing webpack"
    );

    return $this->view->render($response, 'about.php',$data);
});

Step 9. Create a folder called public at the root of the slim directory

Step 10. create a file index.php within public folder and paste script below

<?php

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require('../vendor/autoload.php');

$settings = require __DIR__ . '/../app/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('../resources/views',['baseUrl' => '/slim/public/']);
};


$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__ . '/../app/routes.php';


$app->run();

Step 11. create a file .htaccess file within public folder and paste script below:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

Step 12. Create resouces folder in the root directory.

Step 13.  Create views folder within the resources directory.

Step 14.  Create 3 files within views folder 404.phphome.php and about.php

//404.php

<?php include('layouts/header.php');?>
<header class="bg-dark text-white">
  <div class="container text-center">
    <h1>404</h1>
    <p class="lead">Not Found</p>
  </div>
</header>
<section>
    <div class="container">
        <div class="text-center">
            <h2>This page does not exist</h2>
        </div>
    </div>
</section>
<div class="footer fixed-bottom">
    <?php include('layouts/footer.php');?>
</div>

//home.php

<?php include('layouts/header.php');?>

<header class="bg-dark 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">
                Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium,
                totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
                Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit,
                sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.
            </p>
          </div>
        </div>
      </div>
</section>

<?php include('layouts/footer.php');?>

//about.php

<?php include('layouts/header.php');?>

<header class="bg-dark 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 </h2>
        <p class="lead">
            Lorem ipsum dolor sit amet,
            consectetur adipiscing elit,
            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
            Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        </p>
      </div>
    </div>
  </div>
</section>

<?php include('layouts/footer.php');?>

Step 15. Create a layouts folder and add 2 files footer.php and header.php

//header.php

<!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="Wecode101 Slim 3 Install Webpack">
    <meta name="author" content="">

    <title>Wecode101 Slim 3 Framework</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <!-- 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; ?>">Wecode101 Slim 3 Install Webpack</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 ms-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>

//footer.php

<!-- Footer -->
    <footer class="py-5 bg-dark">
      <div class="container">
        <p class="m-0 text-center text-white">Copyright &copy; Your Website <?= Date('Y'); ?></p>
      </div>
      <!-- /.container -->
    </footer>

  </body>

</html>

At the end of it you should have a file structure looking like this:

The project should now be working. Just start your xampp server and go to http://localhost/slim/public/

You can also create an assets folder within public directory and places your imagescss and js files within the assets folder.

Download project here