Currently learning Symfony. Just wondering about route names, which the book doesn't really seem to say in advance what they are for.
As I understand it, #Route annotations are given a default name based on the bundle, controller and action name. So what's the point in specifying your own route names?
Is it good practice to either leave all routes to have a default name?
Is it better practice to specify your own name for every route?
What if two routes have the same name?
How am I expected to know if I'm using a route name which is already taken, perhaps in another bundle?
Route names are important because your code will often need to build url's. The route name is how you specify which url to construct. Names are also handy for listeners (such as authentication) which process specific url's.
Annotation generated default names are fine but tend to be long and could change on you.
Yes, I would give every route a custom name for convenience and readability. Plus, I don't use annotations. To me at least, storing routes in a central file make the code easier to maintain. It avoids the need to search through multiple controller files trying to determine which code handles which request.
Routes with the same name will replace any previously loaded route. It's useful if you wish to override a route from a third party bundle.
Namespace your route by using some form of your bundle name as a prefix.
Related
As far as I know, currently Yii 2 doesn't have an out of the box method to resolve ambiguity of controller and module names. An example of module hierarchy to describe what exactly I mean:
app\modules\v1\controllers\UserController // resolves the /v1/users and /v1/users/{id} actions
app\modules\v1\modules\user\Module.php // nested module, resolves the /v1/user/... controllers and their actions, e.g. /v1/user/something/{id}
In this case, the UserController conflicts with the user Module. The main reason of the ambiguity is the singular-plural magic of Yii 2 framework. I didn't find an appropriate solution to resolve this ambiguity. Further my ideas how to resolve it.
Rename the module.
Rename the UserController to the UsersController.
Create an additional submodule, and place there the UserController. E.g. app\modules\v1\modules\root\controllers\UserController
I'm not sure that at least one of these options is a quite elegant one and a proper solution in view of the Yii 2 philosophy.
Coming back to the main question, what is a more appropriate approach to resolve this issue by the Yii 2 philosophy? Controller and Module is two different types of objects, which is differently pluralized or not, thus should be right way to separate them in the routing for the described case.
How I usually deal with this depends a bit on how I'm structuring things.
Let's say I have users, departments, orders and maybe some other stuff. All these concepts have their own module in which all interactions take place. If I want to create REST controllers for all these concepts I can choose to add a controller to every module or I can create a dedicated API module for the controllers.
When creating a dedicated module for this purpose I usually name it api, maybe with some nested versioning module(s) inside. So in this situation I would get the following structure app\modules\api\controllers\UserController which would result in the URL /api/user. No ambiguity there and pretty clear what this is meant for.
When adding such a controller to the module itself I choose a better name than just 'UserController'. When asking myself the question 'What does this controller accomplish?/What does it do?' I find that just UserController doesn't cut it; Especially when inside a User module, resulting in /user/user. This controller is probably going to exist alongside one or more different controllers in the User module, all meant for something different. So, usually, I end up naming it just ApiController, resulting in /user/api. Another controller could be the ProfileController. So when looking at the URLs it's pretty clear what /user/api and /user/profile do. Without the ambiguity.
I am not sure I can fully understand the question, but probably you're asking about classname aliases?
use My\Full\Classname as Another;
I'm coming From CodeIgniter to Laravel.
So, is a bad idea using automatic routes to all of controllers?
Route::controller(Controller::detect());
Should I use this instead creating routes in routes.php?
Yes this is bad.
Controller::detect() is actually not present in Laravel 4 because it is a bit broken.
detect() will go through your filesystem and return controller files, but this is a bad idea because the order you define your routes matters. If you have any nested controllers you will find this breaking very easily.
detect() will also return files in a different order depending on the file system, so this leads to a lot of unpredictability.
I would argue that you should define all your routes any ways, it is a lot easier to read and debug.
One of interesting things about Laravel that CI does not have is that for certain pages, you can route directly to the view without needing a controller at all. Think about static pages like 'About Us'. CodeIgniter would need you to set up a controller + view for that, even though the controller will do barely anything. In case of Laravel, you can route directly to a view in this case.
Setting up routes manually will allow you to set these short-circuited routes.
Automatic detection is a bad idea.
You can use routes or use Route::controller('mycontroller') or and array of controllers like Route::controller(array('mycontroller', mycontroller2');
Then you get the benefit, without the autodetect.
in laravel 4 :
you can use Restful Controller like documentation http://laravel.com/docs/controllers#restful-controllers
But
Route::controller() must take two parameters as minimum requirement
first parameter stands for URL respond to ,and second parameter is name of controller
also
you can write third parameter into Route::controller() is an array with names of actions (name of action with HTTP verb )and routes names for this actions
ex:
Route::controller('users','UsersController',array(
'getUsers' =>"listUsers" ,
));
route name for getUsers action is listUsers
Below is a good example to follow for CRUD and general purpose routing
type php arisan controller:make SampleController
edit routes.php and add
Route::resource('sample', 'SampleController');
Then type
php artisan routes to show the newly created routes
I have some fairly complex routing rules, that are only achievable with custom code, and not with the default router.
The router has also to take into account the domain name.
Is it possible (and how) to define my own Router class, that would have a method accepting a Request and returning the bundle/controller name?
To achieve what you're asking, you don't need to completely redefine the router
You can simply write your own class that implements UrlMatcherInterface. If you want to be able to generate URLs that match your scheme as well, you'll have to create another class which overrides UrlGeneratorInterface as well.
In order to take into account the domain name, you'll need to use RequestContext, which is passed to their constructors (it's not well documented, but check Router::get{Matcher,Generator} for the details).
Once your classes are prepared, you can inject them into the router simply by overriding the parameters "router.options.generator_class" and "router.options.matcher_class" in your bundle.
However, it may not be the best approach for what you want - overriding parts of the router like that requires a lot of care to preserve all of the caching.
You might want to consider using Symfony2's normal router, but handing it different route files depending on what the request's domain is. This can be done easily if you configure your web server to set a variable or execute a different front controller depending on the domain name.
Using that information, you can then load a different 'environment' per-request, with the only difference between the different environments being that they use different routing files.
After studying Matthias Noback's tutorial, I have made a slight modification for my CRUD routing builder.
Before and after using CrudLoader can be seen here in routing/crud/acompetencies.yml
It is just a workaround or misuse of resource as you can see in this CrudLoader class.
I don't know if it is right or bad practice. It seems to work well.
refer sonata admin bundle which is having custom routing class classes
symfony 2.5 requires parameter for custom matcher: router.options.matcher_base_class
and class which implements Symfony\Component\Routing\Matcher\RequestMatcherInterface
I have my own routing rules in routes.php, defined for all the pages that should be accessible via URL, such as mywebsite/blog/ and mywebsite/blog/category/category-name, i.e. the structure of my whole website is covered by my custom routes.
Now, I have a lot of elements that make use of requestAction, such as
$websiteabstract = $this -> requestAction(array(
'controller' => 'assets',
'action' => 'displayHomeAbstract'
));
This gives me an error Error: Controller could not be found, probably because I have not defined a route for /assets/displayHomeAbstract. But why do I have to define a custom route for that, when I explicitly state the name of the controller and the action? Shouldn't that bypass the routing altogether?
Either I have not understand Routing at all. Or do I really have to define ALL the possible routes (even those that are only used by requestAction) in my routes.php? I mean, I don't want to allow users to directly access mywebsite/assets/displayHomeAbstract anyway, only via an Element.
Thank you
EDIT: Here is my routes.php http://pastebin.com/aAKBwNZJ
Please have a look at line 128, this is exactly what I do not want since /assets/displayHomeAbstract is ONLY accessed via requestAction.
EDIT: And this is the element, that makes the request: http://pastebin.com/0tK5dYJk
Okay, after extensive discussion with the devs in IRC, I think I understand this well enough to explain to you:
You do have to define your custom routes for your requestAction in this case. requestAction is emulating a full request. It dispatches a request as if accessed using the string url every time, even when the url provided is an array. The book is referring to how when you have a custom route defined in addition to using the default routes (the last line of routes.php), you can use array urls to be agnostic of those routes. However, these array urls rely on the default routes.php in the /lib/ folder and are used to construct a url string. If you're going to have a custom routing pattern, you have to construct the url strings on your own.
Note: the comments below were from earlier versions of this answer.
The key to your problem is understanding the scope of Cake's routing and how it work.
When you define a route in CakePHP, it isn't just used for mapping URLs to controllers. It's also used by the Router for things like generating link addresses and, in your case, mapping the path supplied to requestAction() to a controller. Behind the scenes, Cake is creating a URL string based on your parameters, and then passes it off to the Router to find the correct controller. Since no such route exists, it fails.
As a solution, I would actually recommend not using a controller for that logic. Depending on what it does, a component or a helper may be a better place.
Look at line 156. You commented out the line that loads CakePHP's default routes.
How can I configure Zend_Controller_Router to use the default route by default? For whatever reason unknown, it uses the current route.
This is causing some annoying routing issues, and I don't feel like editing hundreds of links to explicitly use the default route is a reasonable solution to add one custom route.
Your question isn't obvious and is confusing, I will try though.
I am going to assume you do not mean Zend_Controller_Route but in fact are talking about links generated in your views.
You can use baseUrl() like this
About Us
You can set the baseUrl in your Bootstrap like this
Zend_Controller_Front::getInstance()->setBaseUrl("/");
If you are working locally you may want to set it to something like this
Zend_Controller_Front::getInstance()->setBaseUrl("/my-app/public");
Using baseUrl() in your views will now use that path to base all your URLs on. Remember you must wrap your links in baseUrl() for this to work.
The url() helper is not useful for this, this is used for doing things like pagination where you want the current parameters of the request object to be maintained.
Hope that helps.
From Matthew Weier O'Phinney:
The logic you quote above is within
the assemble() method. assemble() may
be called with or without routing
having occurred. By default, the
assumption is that if no route name is
provided, the currently matched route
is utilized -- and if matching was
never performed (or no route matched),
the 'default' route will be used.
The rationale for using the currently
matched route is that typically you
will be routing within the same schema
-- as an example, if you are within a RESTful paradigm, the majority of your
links will be within the current
resource. If we were to follow your
suggestion to utilize the "default"
route when no route is specified (at
least, that's how I interpret what you
said), because the Rest_Route is not
the default route, every single call
to assemble() would require using the
route name -- which others would
deride as causing "headaches."
Personally, I prefer to be explicit
and always specify the route name;
this way I know exactly what route I'm
targetting during assemble(), which
makes debugging easier.
Sounds like the only solution is to set the route for each link to use 'default' instead of leaving it NULL.