PHP Create Api Rest with drivers in Slim3

0

I am learning the Slim3 framework to create apis rest / full, I found several examples, for example in routes.php

$app->group('/v1', function () {
    $this->group('/auth', function () {
        $this->map(['GET', 'POST'], '/login', 'App\controllers\AuthController:login');
        $this->map(['GET', 'POST'], '/logout', 'App\controllers\AuthController:logout');
        $this->map(['GET', 'POST'], '/signup', 'App\controllers\AuthController:signup');
    });

    $this->group('/events', function () {
        $this->get('', 'App\controllers\EventController:getEvents');
        $this->post('', 'App\controllers\EventController:createEvent');

        $this->group('/{eventId}', function () {
            $this->get('', 'App\controllers\EventController:getEvent');
            $this->put('', 'App\controllers\EventController:updateEvent');
            $this->delete('', 'App\controllers\EventController:deleteEvent');            
        });
    });
});

But the controllers are not like creating them, I'm a bit lost with this framework. By the way I searched and found the following Slim 3 Very simple REST Skeleton

I downloaded it unzipped and created the necessary tables, but it does not work, I would say that it has to be installed in some way that I do not know.

    
asked by Webserveis 06.12.2017 в 12:27
source

1 answer

1

Taking the example Controller app / src / Controllers / _Controller.php

The autoload property of the composer.json says that the namespace App is resolved to the subdirectory app/src . Therefore the namespace App\Controllers resolves to the directory app/src/Controllers .

Your controllers should be located in the app/src/Controllers folder and have the form

AuthController.php

<?php
namespace App\Controllers; // <-- sin esto, el autoloader no los encontrará

use Psr\Log\LoggerInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use App\DataAccess\_DataAccess;

/**
 * Class AuthController.
 */
class AuthController extends _Controller
{
 ... acá tus métodos ...
}

EventController.php

<?php
namespace App\Controllers;
use Psr\Log\LoggerInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use App\DataAccess\_DataAccess;

/**
 * Class EventController.
 */
class EventController extends _Controller
{
     ... acá tus métodos ...
}

And call them on routes like:

App\Controllers\AuthController

and

App\Controllers\EventController

Since the namespace where they are defined is App\Controllers with Controllers with C capital.

Within your controllers you have to create the methods to execute the actions defined by your routes ( login , getEvent , etc), since the generic skeleton controller does not have those methods.

    
answered by 06.12.2017 / 12:53
source