RoutingServiceProvider
Convention-based controllers for Silex, (*1)
, (*2)
Requirements
- PHP 5.3+
- monolog/monolog (through the MonologServiceProvider)
Installation
$ composer require achrafsoltani/routing-service-provider
Setup
``` {.php}
$loader = require_once DIR.'/vendor/autoload.php';
// THIS LINE IS MANDATORY, SO THE AUTOLOAD BECOMES AWARE OF YOUR CUSTOM CONTROLLERS
$loader->addPsr4('',DIR.'/src/',true);, (*3)
use Silex\Application;
use AchrafSoltani\Provider\RoutingServiceProvider;
use Symfony\Component\HttpFoundation\Response;, (*4)
$app = new Application();
$app['debug'] = true;, (*5)
// Registering
$app->register(new RoutingServiceProvider());, (*6)
// Defining routes
// You could also implement a custom routes loader from different locations and server a RouteCollection
// instance throough : $app['routing']->addRoutes($routes, $prefix);
$route = new Symfony\Component\Routing\Route('/', array('controller' => 'Foo\Controller\MainController::index'));
// setting methods is optional
$route->setMethods(array('GET', 'POST'));, (*7)
$route2 = new Symfony\Component\Routing\Route('/hello', array('controller' => 'Foo\Controller\MainController::hello'));, (*8)
$app['routing']->addRoute('home', $route);
$app['routing']->addRoute('hello', $route2);, (*9)
// call this rigth before $app->run();
$app['routing']->route();
$app->run();, (*10)
Example Controller
------------
``` {.php}
<?php
namespace Foo\Controller;
use AchrafSoltani\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
// you should extend the base Controller (AchrafSoltani\Controller\Controller) in order to have
// the service container injected
class MainController extends Controller
{
public function index()
{
// services can be accessed as array params: $this->container['key'];
// $this->container is equal to the $app instance
if($this->container['debug'])
{
// or through the get method (symfony Like): $this->container['key'];
return $this->get('twig')->render('form.html.twig');
}
}
public function hello()
{
if($this->get('request')->isMethod('POST'))
{
$username = $this->get('request')->get('username');
return $this->get('twig')->render('hello.html.twig', array('username' => $username));
}
return new Response('no post');
}
}