How to check which #route triggered Controller::Action in Symfony2? - php

In Symfony2 it is possible to define 2 different #routes to get one same Controller and Action?
The thing is: how do you check in that unique action what path or route does the user come from?
Example: Imagine we have an action called "createUserAction" that can be reached both from #routes /common_register and /premium_register.
Inside the action I want to difference between the two kinds of users, to use different forms and create the users according to the route they have entered through (or in general, have a different behavour depending o it).
How do I do that?

In your action, just add additional special route parameter $_route to the method
public function createUserAction ($_route)
{
... //$_route will return the name of your route
}

Have you considered another approach? Just use a single route with a parameter:
/**
*#route ("/register/{type}", requirements={"type" = "common|premium"})
**/
public function createUserAction ($type) {
//use $type to decide what to do
}

Related

Naming routes different from Controller / Database

In a Laravel 5.8 app i want my url's to be in Dutch, however, for consistency and just general easier use, i want to name everything else by their English names. Eloquent will ( as far as i know ) only pass me the proper vars if my Model, Controller, table etc. are all named the same.
Right now, i have a route named /backend/facturen which in English would be /backend/invoices. I have tried using names routes, however, i found that this wasn't what i was looking for.
My route:
Route::resource('/backend/facturen', 'InvoicesController');
My show method inside the InvoicesController:
public function show(Invoice $invoice) {
return view('backend.invoice.show', compact('invoice'));
}
The database table is named 'invoices'.
The only way so far i have got this to work is by renaming my route to:
Route::resource('/backend/invoices', 'InvoicesController');
But, of course, this is not a solution to my problem.
I would like to see all data from the invoices show up on my ( Dutch ) /facturen route.
Resource controllers by default look for a variable with the same name as the (last part of the) URL, so renaming the URL changes that variable as well.
But you can tell Laravel to use a different name:
Route::resource('/backend/facturen', 'InvoicesController')->parameters([
'facturen' => 'invoice'
]);
You could also get the variable itself from the id, without using the laravel magic to correctly detecting the variable from the url:
public function show($id) {
$invoice = Invoice::findOrFail($id);
return view('backend.invoice.show', compact('invoice'));
}
No, you have registered a route pointing to the URL /backend/facturen, to name it, use the name function:
Route::resource('/backend/facturen', 'InvoicesController')->name('backend.invoice.show');
Even then, it won't show that route, when using the view function you need to pass the path to your template, not the route.

Mapping route to another route in Laravel

I am developing an application in the Laravel 5.2 which must have a friendly URL-s. This is not problem with the regular way, where the {slug} wildcard is handled by a controller but I want to make it in a different way.
For now I have only two controllers:
ProductsController#show to show details product
CategoriesController#show to show selected category with listing products which are assigned to it
And routes:
Route::get('product/{product}', 'ProductsCategory#show')->name('product.show');
Route::get('category/{category}', 'CategoriesController#show')->name('category.show');
So when I want to echo a just use route('product.show', compact('product'))
Nothing special until I want to handle different URL-s which are fetched from a database. I thought it will be possible to make an another routes which are assigned to existing and when I use a route(...) helper it will be handled automatically. But it is not. So for example I have a new URL:
domain.com/new-url-for-product.html
so by route it should be assigned to the regular 'product.show' route with some ID, which is handled by route model binder for {product} wildcard. The same for route(..) helper it should print friendly URL-s.
I don't know if my strategy is good. How do you handle with the similar problems?
of course route will handle this automatically. have a look into this. I am just giving you example, you have to set this code as per your need.
route('product.show', 'product'=>'new-url-for-product.html');
will generate this
domain.com/new-url-for-product.html
route('product.show', 'product'=>'new-url2-for-product.html');
will generate this URL
domain.com/new-url2-for-product.html
and so on, and then you have to handle all this in your controller method.
eg: your controller method for this route is ProductsCategory#show which is
public function show($product){
if($product == 'new-url-for-product.html'){
//perform this
}
if($product == 'new-url2-for-product.html'){
//perform this
}
}
this just an example, you have to map this according to your need
Edited Here is the example I tested it
Route::get('/product/{product}.html', ['as'=>'product.show', 'uses'=>'ProductsCategory#show']);

Laravel Route Controller with Forced Parameter

So i have checked out
PHP - Routing with Parameters in Laravel
and
Laravel 4 mandatory parameters error
However using what is said - I cannot seem to make a simple routing possible unless im not understanding how filter/get/parameters works.
So what I would like to do is have a route a URL of /display/2
where display is an action and the 2 is an id but I would like to restrict it to numbers only.
I thought
Route::get('displayproduct/(:num)','SiteController#display');
Route::get('/', 'SiteController#index');
class SiteController extends BaseController {
public function index()
{
return "i'm with index";
}
public function display($id)
{
return $id;
}
}
The problem is that it throws a 404
if i use
Route::get('displayproduct/{id}','SiteController#display');
it will pass the parameter however the URL can be display/ABC and it will pass the parameter.
I would like to restrict it to numbers only.
I also don't want it to be restful because index I would ideally would like to mix this controller with different actions.
Assuming you're using Laravel 4 you can't use (:num), you need to use a regular expression to filter.
Route::get('displayproduct/{id}','SiteController#display')->where('id', '[0-9]+');
You may also define global route patterns
Route::pattern('id', '\d+');
How/When this is helpful?
Suppose you have multiple Routes that require a parameter (lets say id):
Route::get('displayproduct/{id}','SiteController#display');
Route::get('editproduct/{id}','SiteController#edit');
And you know that in all cases an id has to be a digit(s).
Then simply setting a constrain on ALL id parameter across all routes is possible using Route patterns
Route::pattern('id', '\d+');
Doing the above will make sure that all Routes that accept id as a parameter will apply the constrain that id needs to be a digit(s).

Custom routing in code ingniter

I want to use codeigniter for an ecommerce project I'm working on but I think I need some custom routing and I'm not sure if this is possible. I want to be able to use this url:
http://myecommsite.com/store/mens
By default in CI this would call the mens function in the store class. What I actually want is it to call a generic function in the store class and feed in 'mens' as a paremeter. The reason for this is that this site needs to have a mens,womens and childrens section.
Is this possible?
Also When I get further down the line...i.e
http://myecommsite.com/store/mens/category1/category2
how do I make Ci work with this?
Simply define a custom route in application/config/routes.php
Something like, for your url http://myecommsite.com/store/mens
$route['store/(:any)'] = "store/customfunction/$1";
This way all requests will be mapped to your "customfunction" method, which takes the parameter "mens"
You might also want to consdere the __remap() function, which overrides the methods (as opposed to the routing, which overrides the whole URI) Quoting from the manual:
If your controller contains a function named __remap(), it will always
get called regardless of what your URI contains. It overrides the
normal behavior in which the URI determines which function is called,
allowing you to define your own function routing rules.
So you can use a __remap() function in your controller store, and anything will be redirected to that. Any segments after the method name are passed into __remap() as second parameter, and you can use this array with call_user_func_array().
This could come in handy for your second examples of URI. Might be something like
function __remap('mymethod',$array = array())
{
return call_user_func_array('mymethod',$array);
}
and in your method "mymethod" you pick the array element and do what you need to do

Codeigniter multiple controllers vs many methods?

I have a site that has a lot of pages that lye at the root (ex. /contact, /about, /home, /faq, /privacy, /tos, etc.). My question is should these all be separate controllers or one controller with many methods (ex. contact, about, index within a main.php controller )?
UPDATE:
I just realized that methods that are within the default controller don't show in the url without the default controller (ie. main/contact wont automatically route to /contact if main is the default controller ). So you would need to go into routes and override each page.
If all of these are just pages, I would recommend putting them into a single controller. I usually end up putting static pages like this into a 'pages' controller and putting in routes for each static page to bypass the '/pages' in my URLs.
If they are share the same functionality, so they should be in the same controller.
for example, if all of them are using the same model to take content from, so, one controller can easily handle it.
Why in one controller? because you always want to reuse your code.
class someController{
function cotact(){
print $this->getContentFromModel(1);
}
function about(){
print $this->getContentFromModel(2);
}
function home(){
print $this->getContentFromModel(3);
}
private function getContentFromModel($id){
return $this->someContentModel->getContentById($id);
}
}
(instead of print, you should use load a view)
See in my example how all of the function are using the same getContentFromModel function to share the same functionality.
but this is one case only, there could be ther cases that my example can be bad for...
in application/config/routes.php
$route['contact'] = "mainController/contact";
$route['about'] = "mainController/about";
$route['home'] = "mainController/home";
$route['faq'] = "mainController/faq";
$route['privacy'] = "mainController/privacy";
and you should add all of these methods within the mainController.php
You can also save the content of the pages in your database, and them query it. For instance, you can send the url as the keyword to identify the page content
$route['contact'] = "mainController/getContent/contact";
$route['about'] = "mainController/getContent/about";
$route['home'] = "mainController/getContent/home";
$route['faq'] = "mainController/getContent/faq";
$route['privacy'] = "mainController/getContent/privacy";
in this case you only have to create one method named "getContent" in the controller "mainController" and this method will look something like this:
class mainController extends CI_Controller
{
public function getContent($param)
{
$query = $this->db->get_where('mytable', array('pageName' => $param));
// then get the result and print it in a view
}
}
Hope this works for you
The page names you listed should probably be different methods inside your main controller. When you have other functionality that is related to another specific entity, like user, you can create another controller for the user entity and have different methods to display the user, update the user, register the user. But its all really a tool for you to organize your application in a way that makes sense for your domain and your domain model.
I've written a blog post about organizing CodeIgniter controller methods that might be helpful to you. Check it out here: http://caseyflynn.com/2011/10/26/codeigniter-php-framework-how-to-organize-controllers-to-achieve-dry-principles/

Categories