rout the admin controllers in with HMVC - codeigniter

i have a problem with HMVC
i have admin controller in all my modules like this
- modules
- users
- controllers
- admin.php
- users.php
- views
- admin_create_user.php
- admin_view_users.php
- signup.php
- login.php
- news
- controllers
- admin.php
- news.php
- views
- admin_disply_news.php
- admin_create_news.php
- view_news.php
now when go to users admin the URL will be link this
domain.com/users/admin/method .
domain.com/news/admin/method .
but i need it to be
domain.com/admin/users/method
domain.com/admin/news/method

Add these codes in "core/MY_Router.php" Inside "MY_Router" Class -
*(class MY_Router extends MX_Router {** ---code goes in here-- **})*
I tried to do this with routing rules and .htaccess but non of them works. Then I edit the MX_Router code and working perfect but one thing to notice you have to create a sub folder on you'r module's controller call 'admin' and put the controller there to work like this because this way you can use the default routing for modules by calling directly to controller if controller name same as module name.
public $module;
private $located = 0;
protected function _set_request($segments = array()){
$segments = $this->_validate_request($segments);
// If we don't have any segments left - try the default controller;
// WARNING: Directories get shifted out of the segments array!
if (empty($segments))
{
$this->_set_default_controller();
return;
}
if ($this->translate_uri_dashes === TRUE)
{
$segments[0] = str_replace('-', '_', $segments[0]);
if (isset($segments[1]))
{
$segments[1] = str_replace('-', '_', $segments[1]);
}
}
if($segments[0] == 'admin' && isset($segments[1])){
if (isset($segments[2])){
$this->set_method($segments[2]);
$segments[2] = $segments[2];
}else{
$this->set_method('index');
$segments[2] = 'index';
}
$this->directory = '../modules/'.$segments[1].'/controllers/admin/';
$this->module = $segments[1];
$this->class = $segments[1];
$segments[1] = $segments[1];
unset($segments[0]);
$this->uri->rsegments = $segments;
}else{
$segments = $this->locate($segments);
if($this->located == -1)
{
$this->_set_404override_controller();
return;
}
if(empty($segments))
{
$this->_set_default_controller();
return;
}
$this->set_class($segments[0]);
if (isset($segments[1]))
{
$this->set_method($segments[1]);
}
else
{
$segments[1] = 'index';
}
array_unshift($segments, NULL);
unset($segments[0]);
$this->uri->rsegments = $segments;
}
}

You can try to add this to your routes config file:
$route['domain.com/admin/users/(:any)'] = 'domain.com/users/admin/method';
$route['domain.com/admin/news/(:any)'] = 'domain.com/news/admin/method';
When user type domain.com/admin/users/method it will call user controller.
Documentation

Related

Codeingiter & HMVC Unable to locate controller if in 2 level sub folder

If I place a controller in a 2 level sub folder "categories" will not locate it
application > modules > catalog > controllers > forum
application > modules > catalog > controllers > forum > categories
// unable to locate
application > modules > catalog > controllers > forum > categories > Category.php
// able to locate
application > modules > catalog > controllers > forum > Category.php
Question is it possiable to modify MY_Router.php so can locate the folder correct and not effec any thing else.
I am using codeigniter 3.1.0 and HMVC
I have looked at this Unable to access the controller in subfolder but when enable it does not display the default_controller.
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
/* load the MX_Router class */
require APPPATH."third_party/MX/Router.php";
class MY_Router extends MX_Router {
/** Locate the controller **/
public function locate($segments)
{
$this->located = 0;
$ext = $this->config->item('controller_suffix').EXT;
/* use module route if available */
if (isset($segments[0]) && $routes = Modules::parse_routes($segments[0], implode('/', $segments)))
{
$segments = $routes;
}
/* get the segments array elements */
list($module, $directory, $controller) = array_pad($segments, 3, NULL);
/* check modules */
foreach (Modules::$locations as $location => $offset)
{
/* module exists? */
if (is_dir($source = $location.$module.'/controllers/'))
{
$this->module = $module;
$this->directory = $offset.$module.'/controllers/';
/* module sub-controller exists? */
if($directory)
{
/* module sub-directory exists? */
if(is_dir($source.$directory.'/'))
{
$source .= $directory.'/';
$this->directory .= $directory.'/';
/* module sub-directory controller exists? */
if($controller)
{
if(is_file($source.ucfirst($controller).$ext))
{
$this->located = 3;
return array_slice($segments, 2);
}
else $this->located = -1;
}
}
else
if(is_file($source.ucfirst($directory).$ext))
{
$this->located = 2;
return array_slice($segments, 1);
}
else $this->located = -1;
}
/* module controller exists? */
if(is_file($source.ucfirst($module).$ext))
{
$this->located = 1;
return $segments;
}
}
}
if( ! empty($this->directory)) return;
/* application sub-directory controller exists? */
if($directory)
{
if(is_file(APPPATH.'controllers/'.$module.'/'.ucfirst($directory).$ext))
{
$this->directory = $module.'/';
return array_slice($segments, 1);
}
/* application sub-sub-directory controller exists? */
if($controller)
{
if(is_file(APPPATH.'controllers/'.$module.'/'.$directory.'/'.ucfirst($controller).$ext))
{
$this->directory = $module.'/'.$directory.'/';
return array_slice($segments, 2);
}
}
}
/* application controllers sub-directory exists? */
if (is_dir(APPPATH.'controllers/'.$module.'/'))
{
$this->directory = $module.'/';
return array_slice($segments, 1);
}
/* application controller exists? */
if (is_file(APPPATH.'controllers/'.ucfirst($module).$ext))
{
return $segments;
}
$this->located = -1;
}
}
It might be possible, but do you really really need to?
I can sort of see the sense of using...
application > modules > catalog > controllers > forum > Category.php
But I don't see the point of using...
application > modules > catalog > controllers > forum > categories > Category.php
That is going a little too deep for the sake of putting things into their own little boxes.
Personally I would make the Forum a module and have...
application > modules > forum > controllers > categories > Category.php

CodeIgniter Vagrant Redirection Loop

I try to use CodeIgniter with vagrant (machine created with puphpet).
The ip address is 192.168.56.101 and when I try to access the main page I get a loop redirection to /index.php/login
This code is working when trying to access it from inside the VM, but within the host browser I get a loop...
Here is an header from the response :
Refresh:0;url=http://192.168.56.101/index.php/login
And some configuration settings :
// application/config/config.php
$config['base_url'] = 'http://192.168.56.101/';
$config['index_page'] = 'index.php';
Any idea ? I can post more code if it's needed.
Thanks
Edit : as requested, here's more infos :
//index.php
define('ENVIRONMENT', 'development');
if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
$system_path = 'system';
$application_folder = 'application';
if (defined('STDIN'))
{
chdir(dirname(__FILE__));
}
if (realpath($system_path) !== FALSE)
{
$system_path = realpath($system_path).'/';
}
$system_path = rtrim($system_path, '/').'/';
if ( ! is_dir($system_path)){
exit("Your system folder path does not appear to be set correctly. Please open the following file and correct this: ".pathinfo(__FILE__, PATHINFO_BASENAME));
}
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
define('EXT', '.php');
define('BASEPATH', str_replace("\\", "/", $system_path));
define('FCPATH', str_replace(SELF, '', __FILE__));
define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));
if (is_dir($application_folder))
{
define('APPPATH', $application_folder.'/');
}
else
{
if ( ! is_dir(BASEPATH.$application_folder.'/'))
if (is_dir($application_folder))
{
define('APPPATH', $application_folder.'/');
}
else
{
if ( ! is_dir(BASEPATH.$application_folder.'/'))
{
exit("Your application folder path does not appear to be set correctly. Please open the following file and correct this: ".SELF);
}
define('APPPATH', BASEPATH.$application_folder.'/');
}
require_once BASEPATH.'core/CodeIgniter.php';
The main controller :
// application/core/MY_Controller.php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
if ($this->session->userdata('username') === false)
{
redirect('login', 'refresh');
}
}
}
The login controller :
// application/controller/login.php
class Login extends CI_Controller
{
public function index()
{
$username = $this->session->userdata('username');
if ($username === false) {
$view_data = array();
$view_data['alert'] = $this->session->flashdata('alert');
$this->load->view('login',$view_data);
}
else {
redirect('home', 'refresh');
}
}
public function connect() {
$this->load->model('user_model');
$username = $this->session->userdata('username');
if ($username === false) {
$post_username = $this->input->post('username');
$post_password = $this->input->post('password');
$data_bdd = $this->user_model->get_user($post_username);
$this->session->set_flashdata('alert', 'user unknown');
foreach ($data_bdd as $user) {
$this->session->flashdata('alert');
if ($this->encrypt->decode($user->USER_PASSWORD) == $post_password) {
$this->session->set_userdata('username',$post_username);
}
else{
$this->session->set_flashdata('alert', 'incorrect password');
}
}
}
redirect('login', 'refresh');
}
public function disconnect() {
$this->session->unset_userdata('username');
redirect('login', 'refresh');
}
}
I found a solution by removing the following lines :
// application/core/MY_Controller.php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
//if ($this->session->userdata('username') === false)
//{
// redirect('login', 'refresh');
//}
}
}
But I have no longer access to any of the website functionalities (because I am not logged in). I still cannot have access to the login page...

Magento remove param and redirect to same url

I want to remove some URL parameter (like utm_source, but whatever), put it in session and redirect to same page with URL clean of this specific param
I've done in controller_front_init_before like this:
$frontController = $observer->getEvent()->getFront();
$params = $frontController->getRequest()->getParams();
$myParams = array("b");
foreach($myParams as $myParam) {
if (isset($params[$myParam])) {
$customerSession->setData(
$myParam, $params[$myParam]
);
unset($params[$myParam]);
}
}
$frontController->getRequest()->setParams($params); // <- I don't know what to do with that
Now what is the best method to redirect to the same page in request ?
For example redirect http://example.com?a=1&b=2&c=3 to http://example.com?a=1&c=3
Thanks!
$frontController = $observer->getEvent()->getFront();
$params = $frontController->getRequest()->getParams();
$shouldRedirect = false
foreach($params as $key => $value) {
if ($key !== 'b') {
$customerSession->setData($key, $value);
}
else{
unset($params[$key]);
$shouldRedirect = true;
}
}
if($shouldRedirect){
//$url = get url and redirect
//see http://magento.stackexchange.com/questions/5000/add-query-parameters-to-an-existing-url-string
Mage::app()->getResponse()->setRedirect($url);
}

Error 500 "View Not Found" when using SEF and URL Rewriting

I am writing a custom component. I have the view employees. Under this view, I have two layouts, default and modal.
I have a menu item in the toplevel of the main menu, Employees that points to my employee view:
index.php?option=com_mycomponent&view=employees which resolves to domain.com/joomla/employees and displayes the default view as expected.
Now, inside my component I want to link to the modal view, and I do so using JRoute and this url:
index.php?option=com_mycomponent&view=employees&layout=modal
Which resolves to
domain.com/joomla/employees/modal
And produces this error:
500 - View not found [name, type, prefix]: modal, html,
mycomponentView
If I visit index.php using index.php?option=com_mycomponent&view=employees&layout=modal my modal view is displayed.
I have also found that visiting domain.com/joomla/employees/employees/modal displays the correct layout. It is as if joomla is forgetting what view is associated with the menu item at /joomla/employees, and instead looks for the view "modal" unless the extra "employees" is provided in the url.
Also worth noting, domain.com/joomla/employee?layout=modal works fine as well.
Here is what I have for my router.php. This was file was generated for me using the component generator at j-cook.pro.
<?php
defined('_JEXEC') or die;
function MycomponentBuildRoute(&$query){
$segments = array();
if(isset($query['view']))
{
$view = $query['view'];
$segments[] = $view;
unset( $query['view'] );
}
if(isset($query['layout']))
{
$segments[] = $query['layout'];
unset( $query['layout'] );
}
if(isset($query['id']))
{
if(in_array($view, array('edit','view','view','editfacility','view','edit','client','editclient','viewposition','editposition','edit','view','edit','view','view','edit','view','edit','view','edit','view','edit')))
{
$segments[] = (is_array($query['id'])?implode(',', $query['id']):$query['id']);
unset( $query['id'] );
}
};
return $segments;
}
function MycomponentParseRoute($segments)
{
$vars = array();
$vars['view'] = $segments[0];
$nextPos = 1;
if (isset($segments[$nextPos]))
{
$vars['layout'] = $segments[$nextPos];
$nextPos++;
}
if(in_array($vars['view'], array('edit','view','view','editfacility','view','edit','client','editclient','viewposition','editposition','edit','view','edit','view','view','edit','view','edit','view','edit','view','edit'))
&& isset($segments[$nextPos]))
{
$slug = $segments[$nextPos];
$id = explode( ':', $slug );
$vars['id'] = (int) $id[0];
$nextPos++;
}
return $vars;
}
So it is hard to provide an exact answer for this without knowing all the different ways that you want to have urls be parsed. But I will try to give a hint at what will solve this present situation (without hopefully introducing too many new issues!)
The basic issue is that the BuildRoute side does not get a view value so it is not included in the url. On the one hand it is not necessary, because it is in the menu. But it makes it a little harder to parse, so option one is to force there to be a view if you can by changing the top function to start like this:
function MycomponentBuildRoute(&$query){
$segments = array();
if(isset($query['view']))
{
$view = $query['view'];
$segments[] = $view;
unset( $query['view'] );
}
else
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$active = $menu->getActive();
if ($view = $active->query['view']) {
$segments[] = $view;
}
}
...
In this way, if there is a menu item for this and it has a view we will tack it on. This should generate domain.com/joomla/employees/employees/modal.
You could also probably do this logic on the parse side too. This would go instead of the other option above:
function MycomponentParseRoute($segments)
{
$vars = array();
$app = JFactory::getApplication();
$menu = $app->getMenu();
$active = $menu->getActive();
if ($active->query['view']) {
$vars['layout'] = $segments[0];
$nextPos = 1;
} else {
$vars['view'] = $segments[0];
$nextPos = 1;
if (isset($segments[$nextPos]))
{
$vars['layout'] = $segments[$nextPos];
$nextPos++;
}
}
... continue with final check for id
I would probably use the second option but both are an option. By the way, you are also likely to run into issues if you try to use an id without setting a layout.

precontroller hooks in codeigniter

I am using pre-controller hook codeigniter in my project
Description:
we are using subdomain concept and three templates(theme). eg: My site is xyz.com. this is having one first template.
some business signup with this xyz site. for eg. abc(business). We create abc.xyz.com. abc chooses 2 template. abc.xyz.com in browser need to show 2nd template. It is not showing 2nd template. it is showing only 1st template.
When we clicked any link on the site more than once , then the template 2 is set for abc.xyz.com link.
I am using codeigniter. loaded session, database in autoload files.
I used precontroller hook to check whether the url is xyz or any subdomain abc.xyz.com
In hook i am setting template if the url is subdomain one.
But template is not showing when abc.xyz.com is in browser. when i refresh the url for some clicks or clicked any of the header link some count , it showing the actual template of the business abc.
Please help me to fix this issue or provide me some solution .
<?php
class Subdomain_check extends CI_Controller{
public function __construct(){
parent::__construct();
$this->CI =& get_instance();
if (!isset($this->CI->session))
{
$this->CI->load->library('session');
}
}
function checking()
{
$subdomain_arr = explode('.', $_SERVER['HTTP_HOST']); //creates the various parts
if($subdomain_arr[0] == 'www')
{
$subdomain_name = $subdomain_arr[1]; //2ND Part
}
else
{
$subdomain_name = $subdomain_arr[0]; // FIRST Part
}
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
if( $subdomain_name != 'xyz' )
{
$where = array();
$where['subdomain_name'] = $subdomain_name;
$where['status'] = 1;
$this->db->from('subdomain_map');
$this->db->where($where);
$query = $this->db->get();
if($query->num_rows() < 1)
{
header('Location:http://xyz.com/index.php?/error');
}
else
{
$result = $query->row_array();
$this->CI->session->set_userdata('subdomain_id',$result['subdomain_id']);
$this->CI->session->set_userdata('subdomain_name',$result['subdomain_name']);
$org_id = gat_organisationid_using_subdomainid($result['subdomain_id']);
$this->CI->session->set_userdata('organisation_id', $org_id);
if($org_id)
{
$templ_id = get_templid_using_organisationid($org_id);
$org_logo = get_organisation_logo($org_id);
}
if($templ_id){
if($this->session->userdata('pinlogin'))
$this->CI->session->set_userdata('template_set', 4);
else
$this->CI->session->set_userdata('template_set', $templ_id);
}
if($org_logo)
$this->CI->session->set_userdata('org_logo', $org_logo);
}
}
else
{
$this->CI->session->unset_userdata('subdomain_id');
$this->CI->session->unset_userdata('subdomain_name');
if( $this->CI->session->userdata('user_id') && $this->CI->session->userdata('user_category')<=2 )
{
$this->CI->session->unset_userdata('organisation_id');
$this->CI->session->unset_userdata('org_logo');
}
}
}
}
Here is the basic check you need to support custom themes per subdomain
// Gets the current subdomain
$url = 'http://' . $_SERVER['HTTP_HOST'];
$parsedUrl = parse_url($url);
$host = explode('.', $parsedUrl['host']);
// store $host[0], which will contain subdomain or sitename if no subdomain exists
$subdomain = $host[0];
// check for subdomain
if ($subdomain !== 'localhost' OR $subdomain !== 'mysite')
{
// there is a subdomain, lets check that its valid
// simplified get_where using activerecord
$query = $this->db->get_where('subdomain_map', array('subdomain_name' => $subdomain, 'status' => 1));
// num_rows will return 1 if there was a valid subdomain selected
$valid = $query->num_rows() === 1 ? true : false;
if($valid)
{
// set theme, user_data, etc. for subdomain.
}
else
{
// get user out of here with redirect
header('Location: http://' . $_SERVER['HTTP_HOST'] . '/error');
exit();
}
}
Note that when using subdomains with codeigniter, you should set your config > base_url to the following:
$config['base_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/poasty/poasty-starterkit/';
this will ensure things like site_url() and other CI helpers still work.
Reading through your code may I suggest utilizing more of Codeigniters built-in functionality, for example your __construct function has a lot of un-necessary code:
Original code
public function __construct(){
parent::__construct();
/**
* CI already exists
* since this controller extends CI_controller, there is already and instance of CI available as $this.
$this->CI =& get_instance();
*/
/**
* duplicate check, CI checks if library is loaded
* and will ignore if loaded already
if (!isset($this->CI->session))
{
$this->CI->load->library('session');
}
*/
$this->CI->load->library('session');
}
Optimized for Codeigniter
public function __construct()
{
parent::__construct();
$this->CI->load->library('session');
}
I suggest reading up on the Codeigniter user_guide to better understand what codeigniter can do. #see http://codeigniter.com/user_guide/
I hope you find this helpful!

Resources