silexphp / Silex

[DEPRECATED -- Use Symfony instead] The PHP micro-framework based on the Symfony Components
https://silex.symfony.com
MIT License
3.58k stars 718 forks source link

Examples of middleware not working in Silex #1348

Closed DaveSanchez closed 8 years ago

DaveSanchez commented 8 years ago

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

ragboyjr commented 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.

DaveSanchez commented 8 years ago

So it's not necessary to write Request $request, Application $app? so why it's in the documentation? Thank you so much

HeahDude commented 8 years ago

@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) {
    // ...
});`
ragboyjr commented 8 years ago

@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.

DaveSanchez commented 8 years ago

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?

HeahDude commented 8 years ago

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.

HeahDude commented 8 years ago

Can we close here?