Can I get the controller action from given URL?
In my project, I will have different layout used for admin and normal users. i.e.
something.com/content/list - will show layout 1.
something.com/admin/content/list - will show layout 2.
(But these need to be generated by the same controller)
I have added filter to detect the pattern 'admin/*' for this purpose. Now I need to call the action required by the rest of the URL ('content/list' or anything that will appear there). Meaning, there could be anything after admin/ it could be foo/1/edit (in which case foo controller should be called) or it could be bar/1/edit (in which case bar controller should be called). That is why the controller name should be generated dynamically from the url that the filter captures,
So, I want to get the controller action from the URL (content/list) and then call that controller action from inside the filter.
Can this be done?
Thanks to everyone who participated.
I just found the solution to my problem in another thread. HERE
This is what I did.
if(Request::is('admin/*')) {
$my_route = str_replace(URL::to('admin'),"",Request::url());
$request = Request::create($my_route);
return Route::dispatch($request)->getContent();
}
I could not find these methods in the documentation. So I hope, this will help others too.
You can use Request::segment(index) to get part/segment of the url
// http://www.somedomain.com/somecontroller/someaction/param1/param2
$controller = Request::segment(1); // somecontroller
$action = Request::segment(2); // someaction
$param1 = Request::segment(3); // param1
$param2 = Request::segment(3); // param2
Use this in your controller function -
if (Request::is('admin/*'))
{
//layout for admin (layout 2)
}else{
//normal layout (layout 1)
}
You can use RESTful Controller
Route:controller('/', 'Namespace\yourController');
But the method have to be prefixed by HTTP verb and I am not sure whether it can contain more url segment, in your case, I suggest just use:
Route::group(array('prefix' => 'admin'), function()
{
//map certain path to certain controller, and just throw 404 if no matching route
//it's good practice
Route::('content/list', 'yourController#yourMethod');
});
Related
i want to achieve url routing something like www.example.com/alicia
suppose alicia is not a class name or method name just something like passing data in url and with some class i want to access this and want to use it for further process.How i can use it ? Thanks in advance.
You can use Codeigniter's built-in routing, the file route.php is located in your config folder.
there you can add:
$route['alicia'] = 'welcome/index/something';
$route['alicia/:any'] = 'welcome/index/someotherthing/$1';
then in your controller, for example welcome you just create a function like:
public function index($page = null){
if($page=='something'){
// do what you need to do, for example load a view:
$this->load->view('allaboutalicia');
}
elseif ($page=='someotherthing'){
// here you can read in data from url (www.example.com/alicia/2017
$year=$this->uri->segment(2); // you need to load the helper url previously
}else{
// do some other stuff
}
}
documentation on routing and on urlhelper
edit after comment:
in case your uri segment is representing a variable, like a username, then you should use a uri scheme like www.example.com/user/alice and create your route like:
$route['user/:any'] = 'welcome/index/user';
then in your controller welcome
public function index($page=null){
if($page=='user'){
// do what you need to do with that user
$user=$this->uri->segment(2); // you need to load the helper url
}
else{
// exception
}
}
This could be tricky because you don't want to break any existing urls that already work.
If you are using Apache, you can set up a mod_rewrite rule that takes care to exclude each of your controllers that is NOT some name.
Alternatively, you could create a remap method in your base controller.
class Welcome extends CI_Controller
{
public function _remap($method)
{
echo "request for $method being handled by " . __METHOD__;
}
}
You could write logic in that method to examine the requested $method or perhaps look at $_SERVER["REQUEST_URI"] to decide what you want to do. This can be a bit tricky to sort out but is probably a good way to get started.
Another possibility, if you can think of some way to distinguish these urls from your other urls, would be to use the routing functionality of codeigniter and define a pattern matching rule in the routes.php file that points these names to some controller which handles them.
I believe that the default_controller will be a factor in this. Any controller/method situations that actually correspond to a controller::method class should be handled by that controller::method. Any that do not match will, I believe, be assigned to your default_controller:
$route['default_controller'] = 'welcome';
I use :
Route::controller('home', 'HomeController');
in my routes to link all routes to my controller.
I have a getIndex() function in my controller that's executed when I go to '/home'.
I have a case where I'd like to route to '/home/slug', but not always.
I tried using getIndex($slug), but it always asks for '/home/index/{slug?}'. I don't want index to appear.
Not possible using implicit controllers, as far as the documentation goes (as it seems to enforce RESTFUL pattern).
But your can create a new route just for that:
Route::get('home/{slug}','HomeController#slugedIndex');
Route::controller('home', 'HomeController');
Edit: as pointed by Steve the controller method must come after the get method so one does not overwrite the other.
Arthur's answer was :
Route::get('home/{slug}','HomeController#slugedIndex');
Route::controller('home', 'HomeController');
Although it doesn't work, because anything written after 'home/' will now go into the first route (and HomeController#slugedIndex).
I found a workaround though. I took out the route in routes.php :
Route::controller('home', 'HomeController');
Then in my HomeController, I used the missingmethod() that's called whenever a method isn't found in the controller.
Here's the missing method :
public function missingMethod($parameters = array())
{
$sSlug = is_string($parameters) ? $parameters : '';
$oObject = Object::where('slug', $sSlug)->first();
if ($oObject) {
// slug code
}
else {
// 404 code
}
}
I'm trying to write an application that takes a parameter from the url and supplies it to the index function in the default controller. Then decides what to load depending on this parameter either a default home page or a custom page.
$route['(eventguide/:any)'] = 'eventguide';
This code works but only if I have the controller in the url like so:
example.com/eventguide/(parameter)
I don't want to include the controller name. So i'm not exactly sure how to route this.
Ideally the url would look like example.com/(parameter), is this possible?
Yes, you're almost there:
$route['(:any)'] = "eventguide/index/$1";
And in your index() method you fetch the parameter:
public function index($parameter = null){
}
$parameter will now contain anything caught by the :any shortcut, which should be equivalent to (\w)+ IIRC
Since this is a catch-all route, be careful to put any other custom route you want before it, otherwise they will never be reached.
For ex., if you have a controller "admin", your route files should be;:
$route['admin'] = "admin";
$route['(:any)'] = "eventguide/index/$1";
I have set up friendly URLs for a few search result pages, using a custom route for each:
friendly_search_resultpage:
url: /products/my-friendly-alias
param:
module: products
action: search
querystring: searchattribute
querystring2: searchattribute2
This works fine, but when doing the search directly (i.e. browsing to /products/search?querystring=search...) I want to set a <link rel="canonical"> containing the matching friendly URL. This will help Google understand the relation and that there isn't duplicate content.
I put my friendly URL route at the top of routes.yml and hoped for a magic match, but URL parameters aren't recognised in the checking done by symfony. I have dug into sfRoute, with no luck. Is it possible?
I ended up writing a custom routing class to use for these routes, which is executed when url_for() is called. Here is the code:
<?php
class mySearchFriendlyRoute extends sfRoute
{
public function matchesParameters($params, $context = array())
{
// I can't find symfony sorting parameters into order, so I do
// (so that foo=x&bar=y is treated the same as bar=y&foo=x)
ksort($params);
$mine = $this->defaults;
ksort($mine);
if ($params == $mine) {
return true;
}
return false;
}
}
To use, add class: mySearchFriendlyRoute to the routes.yml entry.
Try to use Your own Route:
friendly_search_resultpage:
class: YourRouteClassName
...
And overload sfRoute::generate() there by concrete cannonicalization (return the canonical URL).
This redirects with 301 in my project upon of last sf1.4 revision.
I am currently looking into the PHP Framework Codeigniter and understand the main concepts so far until the Controllers section about _remapping. I have a understanding how _remapping overwrites the behaviour of controller methods over the URI eg from www.example.com/about_me to www.example.com/about-me. What i would like to hear is peoples opinions on what to use- _remapping method or the URI Routing method? Im only asking this as when researching these methods and someone has been troubled on remapping functions, they have been directed to use URI Routing.
So..
1) What is the main common method to use and the pro's over the other one?
2) Is it best to use URI Routing for PHP5 CI version 2 onwards?
I would be grateful to hear your opinions!
Assuming you do not want to use the index (i.e. http://www.yourdomain.com/category) action of your Categories controller, you can use routes.
$route['category/(:any)'] = 'category/view/$1';
Then you simply need a View action within your Category controller to receive the Category name, i.e. PHP.
http://www.yourdomain.com/category/PHP
function View($Tag)
{
var_dump($Tag);
}
Should you still want to access your index action within your controller, you can still access it via http://www.yourdomain.com/category/index
You should use _remap if you want to change the behaviour of default CI's routing.
For example, if you set a maintenance and want to block any specific controller from running, you can use a _remap() function loading your view, and which will NOT call any other method.
Another example is when you have multiple methods in your URI. Example:
site.com/category/PHP
site.com/category/Javascript
site.com/category/ActionScript
Your controller is category but methods are unlimited.
There you can use a _remap method as called by Colin Williams here:
http://codeigniter.com/forums/viewthread/135187/
function _remap($method)
{
$param_offset = 2;
// Default to index
if ( ! method_exists($this, $method))
{
// We need one more param
$param_offset = 1;
$method = 'index';
}
// Since all we get is $method, load up everything else in the URI
$params = array_slice($this->uri->rsegment_array(), $param_offset);
// Call the determined method with all params
call_user_func_array(array($this, $method), $params);
}
To sum up, if the current CI's routing suits to your project, don't use a _remap() method.
$default_controller = "Home";
$language_alias = array('gr','fr');
$controller_exceptions = array('signup');
$route['default_controller'] = $default_controller;
$route["^(".implode('|', $language_alias).")/(".implode('|', $controller_exceptions).")(.*)"] = '$2';
$route["^(".implode('|', $language_alias).")?/(.*)"] = $default_controller.'/$2';
$route["^((?!\b".implode('\b|\b', $controller_exceptions)."\b).*)$"] = $default_controller.'/$1';
foreach($language_alias as $language)
$route[$language] = $default_controller.'/index';