简体   繁体   中英

Global URL parameter in Symfony

I'm trying to get a 'global' parameter into my routing, like this:

/{foo_id}/controller/{another_id}/action

So there's a Foo object, that has id foo_id, that's used by all controllers in all requests (except the home page)

I tried to implement this by simply adding a foo_id parameter to every route. But then I have to add code for loading the right foo to every single controller in the project, and then I have to make sure a user has access to the Foo in every single controller as well. I found another similar question , so I changed my routing to something like this:

foo:
    resource: "@AppBundle/Resources/config/routing-foo.yml"
    prefix: /{foo_id}
    requirements:
        foo_id: \d+

And I added a new controller that's inherited by all other controllers:

class BaseFooController extends Controller
{
    protected $foo;
    public function __construct()
    {
        $request = Request::createFromGlobals();
        $foo_id = $request->attributes->getInt('foo_id');
        // ... set $this->foo ...
    }
}

My though was that I'd just be able to use $this->foo in all other controllers to access the Foo object. I could add access control in this controller as well. But it seems like foo_id isn't accessible at this point.

What would be the best way to do this?

I do not know how to make this with Symfony 2 framework. But you can make a simple script which analyses your routing.yml files with help of regex and adds line "prefix: /{foo_id}" to each route, just after the resource line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM