"Create your own framework... on top of the Symfony2 Components"ãèªãã§ãSymfony2ã¨Silexã«èå³ãããã¦ããã®ã§è²ã å®é¨ãã¦ã¿ã¾ãããã¨ãããã"Create your own framework..."ã§ãã£ãCalendarãSilexã§ã©ãå®è£ ããããèãã¦ã¿ã¾ãã
Silexã¨ããã°
$app->get('/hello/{name}', function ($name) use ($app) { return 'Hello '.$app->escape($name); }); $app->run();
ãããªæãã®ã³ã¼ãã¨ããã¤ã¡ã¼ã¸ãããã¾ãããä¸èº«ã¨ãã¦ã¯part6ã§åºã¦ããSymfony\Component\HttpKernel\Controller\ControllerResolverã®æ´¾çã¯ã©ã¹ã§ããSilex\ControllerResolverã使ã£ã¦ãã¦ã$app->get()ã®ç¬¬äºå¼æ°ã«ã¯ç¡åé¢æ°ä»¥å¤ã®ãã®ã渡ããã¨ãã§ãã¾ãã
ã§ã¯ã©ã®ãããªãã®ã渡ããã¨ãã§ããã®ããControllerResolver#getController()ãè¦ãã¨ä»¥ä¸ã®ããã«ãªã£ã¦ããããã§ãã
1. ã³ã¼ã«ããã¯é
åãã¤ã¾ã array($class_name, $method_name) å㯠array($obj, $method_name)
2. __invokeãå®è£
ãããªãã¸ã§ã¯ã
3. __invokeãå®è£
ããã¯ã©ã¹ã®ã¯ã©ã¹å
4. é¢æ°å
5. ã¯ã©ã¹å::ã¡ã½ããå
ç¡åé¢æ°ã®å ´åã¯2.ã«ãªãã¾ãã"Create your own framework..."ã§ã¯
$routes->add('leap_year', new Routing\Route('/is_leap_year/{year}', array( 'year' => null, '_controller' => 'LeapYearController::indexAction', )));
ã®ããã«ã«ã¼ããå®ç¾©ãã¦ããã®ã§ãåæ§ã«ãSilexã§ã
$app->get('/hello/{name}', 'LeapYearController::indexAction');
ã¨æ¸ããã¨ãã§ãã¾ãããããããã¯ãã¾ãå¬ããããã¾ãããLeapYearController::indexAction()ã«$nameã渡ããã¨ã¯ã§ãã¾ãããç¡åé¢æ°ã使ã£ãæã¨ã¯ç°ãªãããµã¼ãã¹ãã±ã¼ã¿ã¼ã§ãã$appãåç
§ãããã¨ã¯ã§ããªãããã§ãã
(2014/04/01追è¨ï¼å®ã¯ç°¡åã«ã§ãã¾ãã Symfony2/SilexのControllerResolverを読む2 - iakioの日記)
ã§ã¯Symfony2ã®å ´åã¯ã©ããªã£ã¦ããã®ã§ãããããSymfony2ã®ã³ã³ããã¼ã©ã¼ã¯Controller#getContainer()ã§DIã³ã³ãããåç §ãããã¨ãã§ãã¾ããããã¯ãSymfony2ã®ControllerResolverã¯Symfony\Bundle\FrameworkBundle\Controller\ControllerResolverã§ãããããã§ControllerResolver#createController()ããªã¼ãã¼ã©ã¤ããã¦ãã³ã³ããã¼ã©ã¼ãnewããå¾ã«Controller#setContainer()ãå¼ã³åºãã¦ããããã§ãã
Silexã§ãåæ§ã®ControllerResolverãä½ããã¨ãå¯è½ã§ããé常ã«éã«æ¸ãã¨ãããªæãã
<?php require_once __DIR__.'/../vendor/.composer/autoload.php'; use Silex\Application; use Silex\ControllerResolver; class MyControllerResolver extends ControllerResolver { function __construct($app) { $this->app = $app; } protected function createController($controller) { list ($obj, $method) = parent::createController($controller); $obj->app = $this->app; return array($obj, $method); } } class LeapYearController { function indexAction($year) { //... } } $app = new Application(); $app['resolver'] = $app->share(function () use ($app) { return new MyControllerResolver($app); }); $app->get('/is_leap_year/{year}', 'LeapYearController::indexAction'); return $app;
ã¨ã$app['resolver']ã«ç¬èªã®ControllerResolverã®ã¤ã³ã¹ã¿ã³ã¹ãè¿ãç¡åé¢æ°ãã»ãããã¦ããã°è¯ãããã§ãã
ã¨ã¾ãé·ã ã¨æ¸ãã¾ãããããã¯ããã¾ã§å®é¨ã§ãå®éã®ã¨ããããããããæ¹ã¯Silexã£ã½ãã¯ç¡ãã¨æãã¾ãwããã ãããã ãã§ãSilexãSymfony2ãã¨ã¦ãæè»ã«ã§ãã¦ãããã¨ã¯å®æã§ãã¾ããã
ç¶ãäºå®ã