Closed DaveSanchez closed 8 years ago
@DaveSanchez
<?php
require_once __DIR__ . '/vendor/autoload.php';
$app = new Silex\Application();
$app->get('/test', function() {
return 'test path';
});
$app->before(function() {
echo 'before';
});
$app->run();
That works fine.
So it's not necessary to write Request $request, Application $app? so why it's in the documentation? Thank you so much
@DaveSanchez it seems you missed the use statements in your beforeMW.php
:
<?php
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
$app->before(function (Request $request, Application $app) {
// ...
});`
@DaveSanchez, they are optional. Silex will fill those arguments if you have them as parameters. In your example, I didn't see an reference to beforeMw.php
as well.
Your answer is right too, I added the next three lines
**<?php
use Silex\Application; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response;
$app->before(function (Request $request, Application $app) {
});**
But why do I have to do this, if I already added in my start.php file just before require my beforeMW.php file?
It's the way PHP works. In beforeMW.php
you don't declare namespace so you're in the global one: \
. So when type hinting Request
it does not work as it searches for a global \Request
instead of \Symfony\Component\HttpFoundation\Request
.
Can we close here?
I have a problem trying to start working with Middlewares in Silex. This is my start.php file:
` require_once 'vendor/autoload.php';
use Silex\Application; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response;
$app = new Silex\Application();
$app['debug'] = true;
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
$app->register(new Silex\Provider\TwigServiceProvider(), [ 'twig.path' => DIR.'/app/views' ]);
require_once 'routes.php';
$app->run(); `
so my beforeMW.php file looks like this:
`<?php
$app->before(function (Request $request, Application $app) {
});`
I'm taking the example of sessionlabs.org but it's not working, it shows the next error:
Catchable fatal error: Argument 1 passed to {closure}() must be an instance of Request, instance of Symfony\Component\HttpFoundation\Request given in C:\xampp\htdocs\ifix\IFix\app\middleware\beforeMW.php on line 3
please help me, I'm new with frameworks