Commit 17fc85c3 authored by Fabien Potencier's avatar Fabien Potencier

added a way to lazy load mounted applications

parent 5187c9e6
......@@ -417,6 +417,11 @@ one::
Now, blog posts are available under the ``/blog/post/{id}`` route, along side
any other routes you might have defined.
If you mount many applications, you might want to avoid the overhead of
loading them all on each request by using the ``LazyApplication`` wrapper::
$blog = new LazyApplication(__DIR__.'/blog.php');
Pitfalls
--------
......
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Silex;
use Symfony\Component\HttpFoundation\Request;
/**
* A Lazy application wrapper.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class LazyApplication
{
protected $app;
public function __construct($app)
{
$this->app = $app;
}
public function __invoke(Request $request, $prefix)
{
if (!$this->app instanceof Application) {
$this->app = require $this->app;
}
return $this->app->__invoke($request, $prefix);
}
}
......@@ -12,6 +12,7 @@
namespace Silex\Tests;
use Silex\Application;
use Silex\LazyApplication;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
......@@ -69,4 +70,28 @@ class FunctionalTest extends \PHPUnit_Framework_TestCase
$response = $app->handle(Request::create('/hello/Silex'));
$this->assertEquals('Silex', $response->getContent());
}
public function testLazyMountWithAnExternalFile()
{
$tmp = sys_get_temp_dir().'/SilexLazyApp.php';
file_put_contents($tmp, <<<'EOF'
<?php
$app = new Silex\Application();
$app->get('/{name}', function ($name) { return new Symfony\Component\HttpFoundation\Response($name); });
return $app;
EOF
);
$mounted = new LazyApplication($tmp);
$app = new Application();
$app->mount('/hello', $mounted);
$response = $app->handle(Request::create('/hello/Silex'));
$this->assertEquals('Silex', $response->getContent());
unlink($tmp);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment