slimでpimpleを使ってroutingを行う

pimpleを使ってslimのroutingを構造化してみます。

routes.phpの作成

configディレクトリを作成し、routing情報を記述するroutes.phpを作成します。

$ mkdir config
$ vi config/routes.php
<?php

$app->get('/', function() use ($container) {
    $container['ContentsController']->top();
  });

ContentsControllerクラスの作成

index.phpのcontrollerの中に記述していた処理をContentsControllerクラスとして独立させます。
topメソッドの中にcontroller処理を記述してます。

$ mkdir src/Taka512/Controllers
$ vi src/Taka512/Controllers/ContentsController.php
<?php

namespace Taka512\Controllers;

class ContentsController
{
    protected $app;
    protected $service;

    public function __construct(\Pimple $di) {
        $this->app = $di['app'];
        $this->init($di);
    }

    public function init(\Pimple $di) {
        $this->service = $di['NameService'];
    }

    public function top() {
        $name = $this->service->getName();
        $this->app->render('index.html.twig', array('name' => $name));
    }
}

index.phpを修正

controller処理を削除してroutes.phpの読み込み処理を追加します。

$ vi web/index.php
  9 define('PROJECT_DIR', dirname(__FILE__) . '/..');
 10 $app = new Slim(array(
 ~略~
 20 $container = new Pimple();
 21 $container['app'] = $app;
 22 $container['NameService'] = $container->share(function ($container) {
 23     return new \Taka512\Services\NameService($container);
 24 });
 25
 26 $container['ContentsController'] = $container->share(function ($container) {
 27     return new \Taka512\Controllers\ContentsController($container);
 28 });
 29
 30 require PROJECT_DIR.'/config/routes.php';
 31
 32 $app->run();

これでroutes.phpにrouting情報を定義してControllerクラスをモリモリ書いていけるようになりました。
今回の作業をした後のディレクトリ構造は下記となります。

|-- composer.json
|-- composer.lock
|-- logs
|    |-- 2013-06-29.log
|-- templates
|    |-- index.html.twig
|-- config
|    |-- routes.php
|-- vendor
|-- web
|    |-- index.php
|-- src
|    |-- Taka512
|         |-- Controllers
|              |-- ContentsController.php
|         |-- Services
|              |-- NameService.php

参考

http://nesbot.com/2012/11/5/lazy-loading-slim-controllers-using-pimple