Use cases for generated URLs in Symfony2? - php

Coming from a straight PHP and Drupal background, I am recently learning the Symfony2 framework. Currently I am in the routing chapter of the book. This is probably a simple question.
What are some real world use cases for why one would want to generate URLs in a Symfony app? I understand the code but I'm having a bit of trouble determining its practical applications.
I'm referring to this section should you need a refresher.
As always, thank you!
P.S. Symfony is amazing. :)

Basically, you need to generate a URL whenever you need to link to anywhere in your application.
Let's say that you have an application that needs to manage some users. This means that you will probably have URLs like /user/create, /user/edit/(user id) and /user/remove/(user id).
Whenever you display a link to edit a user you need to know on what URL you can find the page that allows you to edit a user. So you need to link to /user/edit/(user id). One solution would be to have this as a fixed link so that in your code you could just write
edit this user
But what if you want to change this URL scheme? Let's say someone is unhappy with the term "user", after all the humans managed by this system are not only users, they are actually "person"s! So now you need to change all the URLs containing "user". Probably there are quite a few places in your app where you have had to hardcode these URLs and now you will need to find and change all of them. Eugh.
But fear not, for Symfony routing comes to the rescue!
Instead of hardcoding these URLs, we can simply let the Symfony router generate them for us. This means that we first need to tell Symfony which routes we have, e.g. by adding the following YAML code to our routes config file:
user_edit:
path: /user/edit/{userId}
defaults: { _controller: AppBundle:User:edit }
requirements:
userId: \d+
This tells our application "Okay, whenever somebody requests a page that looks like /user/edit/{userId}, then you need to call the editAction method in our UserController class in the AppBundle namespace and you need to pass the userId as a parameter. Oh, and also you should only call the controller if userId is a valid integer with at least one number."
So this is how Symfony knows how to map URLs to controllers. But the goodness that comes along with it is that we can use this information for the reverse way as well.
Usually, in our application we do not really care about what the URL looks like for a certain action we want to perform. All we know is that when clicking a certain link, then the browser should jump to a page that allows me to edit a user. And since we just defined a route that takes us right there, we can have Symfony generate the correct URL to achieve just that.
So in your view you can now discard the hardcoded URL from earlier and instead replace it with a route generated by the Symfony router:
edit this user
Now whenever you need to change what the URL actually looks like all you need to do is edit your routing config and not a lot of separate views.

Because, imagine you want to change a given page URL and you've hardcoded it in 10 Twig templates. You will have to modify all these files. On the opposite, when using the routing component:
You would only have to change the URL where the route is defined.
The routing component "takes" care of the current environment you are using (dev, prod...)
Also note that is a bad practice to "switch environment", a typical issue is to hardcode an URL in a Javascript. In this case you can expose your Symfony2 routes in the Javascript by using a bundle like FOSJsRoutingBundle.

I almost immediately realized their use and now I feel silly. :) For those who stop by this question in the future:
Notes about Generating URLs:
Similar to the Drupal l() function, sometimes you need to generate links inside your application based on a variety of parameters.
You don't always want to hardcode your links in case you decide to change paths sometime down the line.
In summary: Think of this as an alternative to using straight anchor tags with href elements all over the app and, instead, keeping things dynamic.

Use case
In the project I'm working I use generateUrl to redirect the user
after creating, editing an entity.
For example after creating a Service entity, I redirect the user to the view
of the just created Service.
Controller
return $this->redirect($this->generateUrl('myentity_view', array('id'=> $id)));
Additional note
In twig files, you can use the path function which call the routing component and generate url with given route name and parameters.

Related

Creating the Post-Redirect-Get pattern with Laravel

I have been used laravel, and I find it's by far the best PHP Framework there is. But even so, I still think that to be able to understand it and PHP MVC's in general, I need to make my own first.
So, as of now, I'm in the process of making my own MVC, I got most things covered. But I wanted to add a feature that is identical to Laravel, which is the Post-Redirect-Get feature, (or so I think).
What I mean is, for those unaware, that if a person visits a link, say localhost/project/laravel/public/profile using the Route::get('localhost/project/laravel/public/profile', 'SomeController#action) He will only be able to view the profile page, from the action() function in SomeController. But when he uses the Route::post('localhost/project/laravel/public/profile', 'SomeController#action2), only when does is the POST request sent from the localhost/project/laravel/public/profile URL, will the action2() function activate.
So, My question is,
How can I make my own Route::get() and Route::post() to work like in laravel
If you want have get and post in the same route you should try this methods
POST and GET in the same pattern

Kohana 3.3 - dynamic menu creation with rights management possible?

I would like to use Kohana 3.3 as a replacement for my self written "framework" which I am currently using for my webapp. Could you please tell me if it is possible to fulfill the following requirements and how to achieve this?
My app consists of several controllers, which I want to access via menu. This menu should be dynamically created, so that a newly created controller will show up immediately. Additionally the menu should exclude controllers which are not accessible for the currently logged in user.
Each controller must be able to check the user's role before executing an action (e.g. global admin, controller-specific admin, regular user). Depending on this role each controller must be able to permit or prohibit access. (Thought about a group membership based method).
I want to use a separate template (as far as I know aka partial) for the menu and for each controller output. They all should be merged with a "frame" template (with header, footer,login info, etc.). I saw there is a special controller for templates (template_controller iirc) - is this the right one to use as my base controller? And should I create a base controller which manages my "template" and nest the other controllers in it somehow?!
Additionally it would be nice if each controller had the ability to recognize the current request as ajax or non-ajax and adjust the rendering accordingly (in most cases "rendering" the whole site again is not desired with ajax).
I would be grateful for every answer!
Thanks in advance.
Yes, but you'd have to search for the controller files yourself AFAIK.
Yes, see before(),
2.1 If you want to keep it in one place you would only have to write a little extra something to specifiy which action requires what privileges. Check out Kohana's Request class for some nice stuff you could use for this (I'd say take a look at the url, uri and request methods, I don't know by hard what exactly they do)
2.2 You could also do it on a per-controller basis; e.g. Controller_Admin could do the following ugly one-liner (check snippet for 2.2 below). I suggest splitting it up a little bit though, e.g. giving your base controller a protected $_user variable which it fills in it's before() method and then use $this->_user instead of Auth stuff.
It's Controller_Template but yes, you got that right ;)
Like this? Request::$current->is_ajax() (http://kohanaframework.org/3.3/guide-api/Request#is_ajax)
Snippet for 2.2:
if ( ! Auth::instance()->get_user()->has('role', ORM::factory('Role', array('name' => 'admin')))
throw new HTTP_Exception_403('Permission denied!');

CodeIgniter core changes

CI looks for Segment[1] for controller (in controller dir) and Segment[2] for Method. Now, I have specific requirement by business application which needs that I do not want CI to look or by force go to controller dir to load but I will have something like this "domainURL/module_identifier_id/controller/method/".
Here, every request will be coming along with its associated Module's Identifier ID which will have complete module's configuration and other data (controller files, module location where it was uploaded, all menus and their URLs which will have same URL mechanism which we want to design for developers to develop modules and upload) stored in DB.
We need to get this ID and play with it to fetch relevent records and point CI to load controller from where we want it and indeed rest for methods etc every thing needs to be working as it is.
I hope you understand what we are looking for that we have our own main controller type file where all of the requests will be coming with customizing protocol as described above and developers will be following it by all means, that there must be module identifier first and then controller, method etc...
Let me know if you have any query to be cleared on?
I think I would just use routes for this:
$route[(:any)/(:any)/(:any)] = '$2/$3/$1';
This should just rearrange your segments the way you want, without completely changing the way the native routing system works.

Removing Controller name from URL in CodeIgniter

Currently in my CI project I have a single controller that handles all things account. Such-as register, login, activation, etc.
My routes work as such...
domain.com/account/login/ or domain.com/account/register/
How can I remove account from the route while also being about to remove the controller from other pages.
I basically want the controller to always be removed. One of my reasons for this is SEO, search engine rank the importunateness of a page based on how deep it is in a website.
The only way I have seem to achieve this is to do some thing like route['activate'] = 'account/activate'; for every single page, which would be a huge hassle.
$route['^(?!other|controllers).*'] = “account/$0″;
Try this :
$route['(:any)'] = "account/$1";
The answer to your question is that you DO have to explicitly set the routes.
How is it going to know which controller a given function is in????
You have to tell it.
use mod_rewrite (if the controller is always the same name)
Ok, I can think of one way to do this, but it is probably gonna be more of a pain than just writing out routes for each function.
You need to extend the Router.php with application/core/MY_Router.php and overide the _validate_request() method. Which basically decides if this this is a valid route or not.
it does a check to see if the controller class exists then fails if it doesn't exist.
You need to replace this with some code which assumes no controller segment, then scans thru each of your controllers and checks if it contains the method called (it will be segment 1, since theres no controller).
Now the tricky part, at this point in the CI lifecycle your controller obviously isnt loaded, so you cant examine it using method_exists() yet.
You need to load your controllers one at a time, and then for each one run
method_exists($loaded_class, $method_name)
and if its true, then set then go ahead and call:
$this->set_class('the_name_of_the_scanned_class_which_had_the_method');
Then CI can keep going on as normal and it will load your methods without the user ever know what controller it loaded from.
.. probably not worth the hassle imho. A much easier solution would be to just have one controller and one route to that controller.

dynamic action names in codeigniter or any php mvc framework

I've noticed many sites are able to use a username or page title as an action. How is this done?
For example instead of www.example.com/users/my_username (where the users action is generic and responsible for fetching user data) how could I make this www.example.com/my_username?
Thanks very much.
All modern frameworks follow router ideology. So for this task you just need to write yet another route.
How to do this - is a specific task for particular framework.
In CodeIgniter it would be a route like zerkms said. You can define routs in /system/application/config/routes.php. Here's the CodeIgniter documentation on URI routing. Essentially you take the part of the URL (such as the username) specified in your route as a variable and can do a lookup against your db with it.
With mod_rewrite you could write a rule that redirects www.example.com/user/my_username (or without the user) to www.example.com/user/?name=my_username.

Categories