4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SilexでPage Forwarding

Posted at

Silexでのforwardの方法は ドキュメントにも書かれており、

forward.php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

$app->get('/', function () use($app) {
    // redirect to /hello
    $subRequest = Request::create('/hello', 'GET');

    return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
});

のように、Silex\Application::handle()を使用するのですが、
これ毎回書くの面倒ですよね。

ということで、こんなtraitを用意し、

RequestSupports.php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

trait RequestSupports {
    public function forward($uri, $method = null) {
        if (!isset($method)) {
            $method = $this['request']->getMethod();
        }
        
        return $this->handle(
            Request::create($uri, $method), 
            HttpKernelInterface::SUB_REQUEST
        );
    }
}

Applicationにmix-inしてあげれば、

MyApplication.php
class MyApplication extends \Silex\Application {
    use RequestSupports;
}
usage.php
$app->forward('/');

と、簡潔に書くことができるようになります。

traitを使用するため、残念ながら、5.4以降限定となってはしまいますが....。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?