Authentication

In previous example we already had access to database and user model which allow us to use user model globally as model to create user login. To create authentication in Slim, we have to create authentication controller, View and create a form where user can sign up with account and last we have to insert new user login record in our database.

1. Create user login View

Inside the resources/view create new folder called auth and add new file signup.twig

{%  extends 'templates/app.twig' %}

{% block content %}
 <div class="row">
 <div class="col-md-8 col-md-offset-2">
 <div class="card">
 <div class="card-header text-center">Sign up</div>
 <div class="card-body">
 <div class="card-text">
 <form action="{{ path_for('auth.signup') }}" method="post" 
                            autocomplete="off">
 <div class="form-group">
 <label for="email">Email</label>
 <input type="email" name="email" id="email" 
                                placeholder="your@domain.com" class="form-control">
 </div>
 <div class="form-group">
 <label for="name">Name</label>
 <input type="text" name="name" id="name" 
                                    class="form-control">
 </div>
 <div class="form-group">
 <label for="password">Password</label>
 <input type="password" name="password" id="password" 
                                    class="form-control">
 </div>
 <button type="submit" class="btn btn-default">Sign Up</button>
 </form>
 </div>
 </div>
 </div>
 </div>
 </div>
{% endblock %}

Step 2: Define User Model in app/Models/User.php 

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

Class User extends Model {
 protected $table = 'users';

 protected $fillable = [
 'email',
 'name',
 'password',
    ];

}
Step 3: Create authController
Inside the app/Controllers folder add new folder called Auth and add new file called AuthController.php. In AuthController.php we have two methods
1. getSignUp ( to render the view template auth/signup.twig file)
    This method is called when we sent get request to http://localhost/testSlim/public/auth/signup
2. postSignUp  (This is called when we submit the form)
    This method is called when we submit the login form, it will create new user and insert new user into our      database table user.

Add following code

<?php

namespace App\Controllers\Auth;

use App\Models\User;
use App\Controllers\Controller;

class AuthController extends Controller {

 public function getSignUp($req, $res){
 return $this->view->render($res, 'auth/signup.twig');
    }

 public function postSignUp($req, $res){
 // var_dump($res->getParams());
       $user = User::create([
 'name' => $req->getParam('email'),
 'email' => $req->getParam('name'),
 'password' => password_hash($req->getParam('password'), PASSWORD_DEFAULT), 
        ]);

 return $res->withRedirect($this->router->pathFor('home'));
    }
}
For the password we are using php password hashing API, first argument is data that we want to hash and second argument is algorithm we want to use.

Step 3: Define route for signup get and post methods, add following code in app/routes.php 

<?php

$app->get('/', 'HomeController:index')->setName('home');
$app->get('/auth/signup', 'AuthController:getSignUp')->setName('auth.signup');
$app->post('/auth/signup', 'AuthController:postSignUp');
We can attach name to route for controller, so we can used is as reference in our code of view and controller.

Step 4: Define AuthController in our bootstrap/app.php 

$container['AuthController'] = function($container) {
 return new \App\Controllers\Auth\AuthController($container);
};
Step 5: Insert new user account in our database table
    http://localhost/testSlim/public/auth/signup

Eloquent with Slim

We can use a database ORM such as Eloquent to connect your SlimPHP application to a database. We need to setup the databse and Model in best possible way. We are using Lavravel Eloquent ORM which provides a beautiful, simple ActiveRecord implementation for working with your database. We can use Eloquent outside of Lavravel and can easily use in our Slim project. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

Step 1: Define Database schema
Inside phpmyadmin create a database name slimDB and add new table called users. Add following field ID, Name, Email, Password, Created_at, update_at. Where ID is integer, auto increment and primary field. Define database as utf8_unicode_ci.

Step 2: Install illuminate/database
composer require illuminate/database

Step 3: Configure the databse
In bootstrap/app.php we have set up the database configuration and we need to a way to define eloquent within our Slim project.

<?php

session_start();

require __DIR__ . '/../vendor/autoload.php';
$app = new \Slim\App([ 
    'settings' => [
        'displayErrorDetails' => true,
        'db' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'database' => 'tamoslim1',
            'username' => 'root',
            'password' => 'tamo1959',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
        ]
        ],
]);
$container = $app->getContainer();
$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($container['settings']['db']);
$capsule->setAsGlobal();
$capsule->bootEloquent();

$container['db'] = function ($container) use ($capsule) {
    return $capsule;
};
The capsule is way the Laravel let us to use it component outside of the Laravel. Now we can access our database . Now we need booted it globally, so we can use Model and we can access it via  through container within our controller.

Now test database or eloquent in our app/Controllers/homeController.php add this code.

<?php

namespace App\Controllers;

use Slim\Views\Twig as View;

class HomeController extends Controller {

    public function index($req, $res){
        $user = $this->db->table('users')->find(1);
        var_dump($user->email);
        die();

        return $this->view->render($res, 'home.twig');
    }
}

Slim

What is SLIM Framework?
PHP micro framework that helps PHP developers quickly and easily write web applications and APIs. Think of it as a core set of tools with which a developer can build amazing things.”

Called micro framework because Slim framework which focus on the basic needs required of a web application such as: received a HTTP request, send request to appropriate code, and restore HTTP responses.

How to install SLIM Framework?
Before readers install SLIM framework it would be nice readers adjust a PHP
version used. There are two requirements which readers must fullfill.
1. We need a web server like Nginx or Apache.
3. Slim 3 support PHP Version 5.5 or latest

For installing Slim we need to install web server, here we have using xampp for Apache server and also we have to install composer.

1. Manually installing the slim framework
2. Installing Slim from slim skeleton.
Step 1: Create slim project

$ cd xampp\htdocs
$ mkdir firstSlim
$ cd firstSlim

# install slim via composer
$ composer require slim/slim "^3.0"

The above command will create a composer.json file in your project root:

Step 2: Create new filw index.php add required dependencies.
Now just create index.php file containing:

<?php
require 'vendor/autoload.php';

$app = new Slim\App();
$app->get('/hello', function ($request, $response, $args) {
    $response->write("Hello World");
    return $response;
});
$app->run();

Now goto browser and hit testSlim url like http://localhost:8080/firstSlim you will see hello World. That’s it.

composer require slim/twig-view

To test the working of slim add following code in index.php for test. In root folder create create src/public, add two file index.php and .httaccess. In index.php add the following code

<?php
require 'vendor/autoload.php';

$app = new Slim\App();
$app->get('/hello/{name}', function ($request, $response, $args) {
    $response->write("Hello, " . $args['name']);
    return $response;
});
$app->run();

In .httaccess add following code

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

To make your life easier, you should create a .htaccess file that defines a clean URL structure. In the public directory, make a .htaccess file and add the following code in it. This will provide a clean URL structure for the PHP file. (this just means that you don’t have to include PHP filenames in the URL calls). If the index file is located in a different folder (for instance, the public folder) and the .htaccess file is on the root, you can insert the full path of the index file in the last line:
RewriteRule ^ public/index.php [QSA,L]

we can access by
php -S localhost:8000 or
http://localhost/testSlim/public/

Upgrade slim 3.0 to 3.5: first change composer.json and run
composer update