Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Slim Framework Create Controller

I am creating an API using the Slim framework. Currently I use a single file to create the route and pass a closure to it:

$app->get('/', function($req, $resp){
//Code...
})

But I realise that my file has grown rapidly. What I want to do is use controllers instead, so I will have a controller class and just pass the instance/static methods to the route, like below

class HomeController
{
   public static function index($req, $resp){}
}

and then pass the function to the route

$app->get('/', HomeController::index);

I tried this, but it does not work, and I wonder if there is a way I can use it to manage my files.

like image 505
James Okpe George Avatar asked Dec 02 '22 13:12

James Okpe George


2 Answers

Turn the controller into a functor:

class HomeController
{
    public function __invoke($req, $resp) {}
}

and then route like this:

$app->get('/', HomeController::class);

For reference, see

  • http://www.slimframework.com/docs/objects/router.html#how-to-create-routes
  • http://www.slimframework.com/docs/objects/router.html#route-callbacks.
like image 197
localheinz Avatar answered Dec 05 '22 22:12

localheinz


PHP 5.6 Slim 2.6.2

require 'vendor/autoload.php';

class HelloController {
    public static function index()  {
        global $app;

        echo "<pre>";
        var_dump($app->request);
        echo "</pre>";
    }
}

$app = new \Slim\Slim();
$app->get('/', 'HelloController::index');
$app->run();

Update: PHP 5.6 Slim 3.0.0

require 'vendor/autoload.php';

class HelloController {
    public static function hello(\Slim\Http\Request $req, \Slim\Http\Response $response, $args)  {
        echo "<pre>";
        var_dump($args);
        echo "</pre>";
    }
}

$app = new \Slim\App();
$app->get('/hello/{name}', 'HelloController::hello');
$app->run();

The problem with class based routing in Slim 3.0 is access to $this/$app. I think you will need to use global $app to access it.

In my pet project I use route groups with require_once. Something like

$app->group('/dashboard', function () {
    $this->group('/auctions', function () use ($app){
        require_once('routes/dashboard/auctions.php');
    });
    $this->group('/rss', function () {
        require_once('routes/dashboard/rss.php');
    });
    $this->group('/settings', function () {
        require_once('routes/dashboard/settings.php');
    });
});

Looks not as beauty as could be with pure classes but works like expected with all features accessible without additional coding.

like image 20
CrazyCrow Avatar answered Dec 06 '22 00:12

CrazyCrow