slim 3 php-di

dentro de tu aplicacion slim

composer require php-di/slim-bridge
ir a composer.json, agregar la sgt linea

"autoload": {
      "psr-4": {
         "App\\": "src/"
      }
    }


ejecutar por consola

composer dumpautoload

This means that you have a directory called src and any class inside that directory, will have a base namespace of App and then any other directories act as sub-namespaces.
i.e. if you have a file called src/Controllers/UserController.php, then the class definition in that file will be:
<?php
namespace App\Controllers;
class UserController
{
    // methods here
}

reemplazar el contenido del public/index.php

por este otro

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use \Psr\Http\Message\RequestInterface;
use \Psr\Http\Message\ResponseInterface;


use App\Controllers\TodoController;

$app = new \DI\Bridge\Slim\App;

/*$app->get('/', function (RequestInterface $request, ResponseInterface $response) {
    $response->getBody()->write('Hello world!');

    return $response;
});
*/
$app->get('/[{greetee}]', TodoController::class . '::index');

// Register middleware
require __DIR__ . '/../src/middleware.php';

$app->run();



para probar la inyection de dependencias vamos a instalar mustache que resuelve vistas para inyectarselo a nuestro controller

composer require mustache/mustache


luego

<?php
namespace App\Controllers;

use \Psr\Http\Message\RequestInterface;
use \Psr\Http\Message\ResponseInterface;

class TodoController
{
private $mustache;

    public function __construct(\Mustache_Engine $mustache)
    {
       $this->mustache = $mustache;
    }

    public function index(RequestInterface $request, ResponseInterface $response, $greetee = null)
    {
    /*
        $response->getBody()->write('HOlaaaaaaaaaaaaaaaaaa!');

        return $response;*/

       /* $response->getBody()->write(
            $this->mustache->render('Hello {{ greetee }}', [
                'greetee' => 'World!'
            ])
        );*/

$response->getBody()->write(
            $this->mustache->render('Hola {{ greetee }} ', [
                'greetee' => $greetee ?? 'Mundo!'
            ])
        );
        return $response;
    }
}

When our container sees that TodoController needs a Mustache_Engine, it tries to create one to fulfill the dependency. Behold, the power of autowiring!




No hay comentarios:

Publicar un comentario

linux ubuntu mint actualizar chrome

 desde una terminal: $ sudo apt update $ sudo apt install google-chrome-stable