How to route all module of HMVC to single controller CI - codeigniter

i use HMVC with CI last version andi want to route all module of HMVC to a controller CI
If i use
$route[‘admin/(:any)’] = “admin/”;
$route[’(:any)’] = “index/index/$1”;
$route[’(:any)/(:any)’] = “index/index/$1/$2”;
$route[’(:any)/(:any)/(:any)’] = “index/index/$1/$2/$3”;
is not a solution, because a url can have many segments
i want to route the controller, method, and all parameters, like this:
$route[’(:any)/(:any)/ *all parameters *’] = “index/index/$1/$2/ *array($parameters)*”;
or how can stop the route of HMVC, i don`t need the route of HMVC.
Pls help.
Thanks, Jhon.

You don't need routing, codeigniter does this already.
From a fresh CI install, playing with the welcome controller:
public function index()
{
$args = $this->uri->uri_to_assoc();
echo "<pre>";
print_r($args);
echo "</pre>";
// $this->load->view('welcome_message');
}
Visiting [http://localhost/codeigniter2.1.2/index.php/welcome/index/param1/param1_value/param2/param2_value/param3/etc]
yields this:
Array
(
[param1] => param1_value
[param2] => param2_value
[param3] => etc
)
So you have your controller [welcome], your function [index] and everything after are parameters; no need to mess with routing.
You don't need to account for every possible parameter that might be routed.
You can use a route like this:
$route[‘admin/(:any)’] = “admin/”;
$route[’(:any)/(:any)/(:any)’] = “index/index/$1/$2/$3”;
Then every URL except admin/* will be routed to index/index. From that point, you can grab the parameters like I posted above or via $this->uri->segment(n); where n is the segment you want (so, $this->uri->segment(3) would return $1 from the route above).

Related

Find a Controller by the Route in Laravel

I have a route and I need to know a controller that would be used for it.
I know how to find a controller for the current route:
Illuminate\Support\Facades\Route::currentRouteAction();
But how can I do the same for other routes?
Route Facade is the answer. It can return Illuminate\Routing\RouteCollection object.
and then you can get Illuminate\Routing\Route object by route name.
Every Route triggers multiple actions such as middleware and controller methods. So we need only the controller.
use Illuminate\Support\Facades\Route as RouteFacade;
/*#var $route Illuminate\Routing\Route*/
$name = 'admin.reports.my-report.get-filters'; // sample route name
$route = RouteFacade::getRoutes()->getByName($name);
$controllerAction = $route->action['controller'];
$controller = explode('#', $controllerAction)[0];
logger($controller);
P.S.
In cases like that - remember to make a unit test for this functionality to be sure it works as you upgrade your laravel.

configuring dynamic url's in router

I'm using Codeigniter. Basically what I want is to remove the Controller name (Home) from the url.
Those urls look like:
http://localhost/mechanicly/Home
http://localhost/mechanicly/Home/about
http://localhost/mechanicly/Home/contactus
now there are two ways I can remove the Home controller:
static definition of every url inside route:
$route['about'] = "Home/about";
$route['contactus'] = "Home/contactus";
I can use call backs in routes in Codeigniter:
$route['(.+)'] = function ( $param ) {
if( strpos( $param, "Admin" ) !== false ) {
echo $param;
return "Admin/".$param;
}
else{
echo $param;
return "Home/".$param;
}
};
this logic is much better as it is generic and I don't have to create new routes every time for new method inside the controller.
It is working fine for the client controller which is Home but I have another controller named as Admin and I want to redirect Admin requests to the Admin controller and Home request to the Home Controller.
Why does above code work fine for the Home controller but returns
not found
when I validate for the Admin controller?
I am using CI version 3.x
If you really want to get crazy, you could parse the methods from the controller file and programatically create the "static" approach.
Pseudo code here
$controller_file_contents = file_get_contents('path/to/controller.php');
$controller_methods = function_that_parses_methods_from_file($controller_file_contents);
foreach ($controller_methods as $controller_method) {
$route[$controller_method] = "Home/" . $controller_method;
}
How function_that_parses_methods_from_file works is probably gonna involve a regex, something like function \w+. If you go with this approach, try to keep the controller as small as possible by offloading as much logic as possible into models, which is often a good idea anyways. That way the performance impact in the router is as small as possible.
Alternatively, you may be able to parse the controller using get_class_methods if you can figure out how to load the controller into memory inside the router without conflicting when you need to load the controller using the router or causing too much performance issues.
Pretty goofy, but every method you create in that controller will automatically create a route.
you can create your menu(url´s) from db like
tbl_menu tbl_level
---------- -------------
id id
fk_level level
name dateUP
dateUP active
active
In your controllers you need to call the correct menu by session or wherever you want
then you can has this in your route.php
$route['(.+)'] = 'int_rout/routing/' . json_encode($1);
in your controller Int_rout.php
public function routing ( $param ) {
$routing = json_decode($param);
$routing = explode('/', $routing);
//$menu -> get menu from model
foreach($menu as $item){
if($routing[0] === $item->name){
//$level -> get level from model
$redirect = $level->level;
}
}
//the final redirect will be like
//admin/user or admin/user/12
//public/us
$params = ( empty($routing[1])) ? '' : '/' . $routing[1];
redirect($redirect . '/' . $routing[0] . $params, 'refresh');
}

Laravel 5.3 dynamic routing to multiple controllers

I'm using Laravel 5.3. I have a bunch of urls that I'd like to handle with a single route, to multiple controllers.
e.g.
GET /admin/foo => FooController#index
GET /admin/foo/edit/1 => FooController#edit($id)
GET /admin/bar => BarController#index
GET /admin/bar/edit/1 => BarController#item($id)
GET /admin/baz => BazController#index
GET /admin/baz/edit/1 => BazController#item($id)
etc.
I want to be able to detect if the controller exists, and if not throw a 404 or route to a default controller (which may throw a 404).
Below is what I've got so far, but I'm not sure what I'm doing. Shouldn't I be instantiating the controller using the service container? I don't think I should be hardcoding namespaces like this. And my handling of the id parameter is sketchy. Perhaps I should have two routes for these two patterns or something?
Route::get('/admin/{entityType}/{action?}/{id?}', function ($entityType, $action = 'index', $id = null) {
$controllerClass = 'App\Http\Controllers\\' . ucfirst($entityType) . 'Controller';
$controller = new $controllerClass;
$route = app(\Illuminate\Routing\Route::class);
$container = app(\Illuminate\Container\Container::class);
return (new Illuminate\Routing\ControllerDispatcher($container))->dispatch($route, $controller, $action);
abort(404);
});
I'd recommend you to define a route for every controller explicitly. This is the best way to build a maintainable app.
Also, if using one route and one method is an option (with right architecure it is) use one route:
Route::get('/admin/{entityType}/{action?}/{id?}', 'Controller#method');
And one entry point:
public function method($entity, $action = null, $id = null)
{
// Handle request here.
https://laravel.com/docs/5.3/routing#parameters-optional-parameters

Laravel how to route old urls

I am using Laravel 4.
I have an old url that needs to be routable. It doesn't really matter what it's purpose is but it exists within the paypal systems and will be called regularly but cannot be changed (which is ridiculous I know).
I realise that this isn't the format url's are supposed to take in Laravel, but this is the url that will be called and I need to find a way to route it:
http://domain.com/forum/index.php?app=subscriptions&r_f_g=xxx-paypal
(xxx will be different on every request)
I can't figure out how to route this with laravel, i'd like to route it to the method PaypalController#ipbIpn so i've tried something like this:
Route::post('forum/index.php?app=subscriptions&r_f_g={id}-paypal', 'PaypalController#ipbIpn');
But this doesn't work, infact I can't even get this to work:
Route::post('forum/index.php', 'PaypalController#ipbIpn');
But this will:
Route::post('forum/index', 'PaypalController#ipbIpn');
So the question is how can I route the url, as it is at the top of this question, using Laravel?
For completeness I should say that this will always be a post not a get, but that shouldn't really make any difference to the solution.
Use this:
Route::post('forum/{file}', 'PaypalController#ipbIpn');
And then in the controller, use
public function forum($file) {
$request = Route::getRequest();
$q = (array) $request->query; // GET
$parameters = array();
foreach($q as $key => $pararr) {
$parameters = array_merge($parameters, $pararr);
}
}
You can then access the get parameters via e.g.
echo $parameters['app'];
you can use route redirection to mask and ending .php route ex:
Route::get('forum/index', ['uses'=> 'PaypalController#ipbIpn']);
Route::redirect('forum/index.php', 'forum/index');

Codeigniter - url segment replace or redirect

I have a base controller (base) which all other controllers extend from.
Anything placed here will override other controllers, the redirects will be here.
URLs example:
http://domain.com/controllerone/function
http://domain.com/controllertwo/function
http://domain.com/controllerthree/function
Using the code below. will give me the controller name
$this->uri->segment(1);
Each of the above controllers need to be redirected to separate URLs, but the funcation part should not change:
http://domain.com/newcontrollerone/function
http://domain.com/newcontrollertwo/function
http://domain.com/newcontrollerthree/function
In my base controller i want the following logic:
$controller_name = $this->uri->segment(1);
if($controller_name === 'controllerone'){
// replace the controller name with new one and redirect, how ?
}else if($controller_name === 'controllertwo'){
// replace the controller name with new one and redirect, how ?
}else{
// continue as normal
}
i was thinking i should use redirect() function and str_replace(), but dont know how efficient these would be. Ideally i do not want to use the Routing class.
thanks.
try
header("Location:".base_url("newcontroller/".$this->uri->segment(2)));
Simple Solution using segment_array:
$segs = $this->uri->segment_array();
if($segs[1] === 'controllerone'){
$segs[1] = "newcontroller";
redirect($segs);
}else if($segs[1] === 'controllertwo'){
$segs[1] = "newcontroller2";
redirect($segs);
}else{
// continue as normal
}
CodeIgniter's URI Routing, should be able to help in this case. However, if you have a good reason not to use it, then this solution may help.
The potential redirects are in an array, where the key is the controller name being looked for in the URL and the value is the name of the controller to redirect to. This may not be the most efficient but I think it should be easier to manage and read than a potentially very long if-then-else statement.
//Get the controller name from the URL
$controller_name = $this->uri->segment(1);
//Alternative: $controller_name = $this->router->fetch_class();
//List of redirects
$redirects = array(
"controllerone" => "newcontrollerone",
"controllertwo" => "newcontrollertwo",
//...add more redirects here
);
//If a redirect exists for the controller
if (array_key_exists($controller_name, $redirects))
{
//Controller to redirect to
$redirect_controller = $redirects[$controller_name];
//Create string to pass to redirect
$redirect_segments = '/'
. $redirect_controller
. substr($this->uri->uri_string(), strlen($controller_name)); //Function, parameters etc. to append (removes the original controller name)
redirect($redirect_segments, 'refresh');
}
else
{
//Do what you want...
}

Resources