How to use multiple controllers and model in codeigniter 3.1.4? - php

I am very new to codeigniter and i am using the version 3.1.4.
I have 2 users in my system and i wanted to use 2 different controllers in the same system, since i felt that using one single controller will have too many functions in it.
what i found as solution was similar to these: How do you use multiple controllers in CodeIgniter?
i dont find any $route['(:any)'] in my routes file.
Please help me solve this with every step since i am very new.
I want to know how to route it and how to call the function (in both the controllers) in a view page as well as model.
Also i need help in using 2 models.(for that i think i just need to mention the model name while calling the fucntion in model)need advice.

You can use routing for all user to redirect to same controller with the routing rule:
$route['users/(:any)'] = "users/index/$1";
for example-
I have two user manager and admin
http://localhost/project/users/manager/create
http://localhost/project/users/admin/create
both request redirect to users/index and now you can get value of the function using
$func = $this->uri->segment(3, 'list');
$user_type = $this->uri->segment(2, 0);
Now use switch case for call a function
switch ($func) {
case 'create':
$this->create($user_type);
return;
default:
$this->view($user_type);
return;
}

Related

Use database from annotation.php file to create dynamic routes in symfony

I am trying to create a dynamic router for my symfony application where on a base of some condition I want to set the prefix of a route, the condition based prefix is working as I use the statically coded condition, see my router with dummy route, main symfony route for Bundle
(config/routes/annotation.php)
<?php use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
return function (RoutingConfigurator $routes) {
$resultRout = $routes->import('#MyCustomBundle/Controller/Test/', 'annotation')
->defaults(['_locale' => '%locale%'])
->requirements(['_locale' => '%app_locales%']);
// get $validate value from database
if ($validate) {
$resultRout->prefix('/{_locale}/app/{default_path}/');
} else {
$resultRout->prefix('/{_locale}/site/{new_path}/');
}
};
The issues I face are:
1: I need to clear route caching every time for different route condition. Is there a way to stop route caching?
2: I want to access database so that I can create $validate as per the DB values. How to load entity manager?
Also if there is a better way to achieve this type of routing please suggest.

PHP Laravel extending resource routing

Laravel routing functionality allows you to name a resource and name a controller to go with it. I am new to Laravel and would like to know if anyone knows how to extend the resources method in the route class provided.
Basically say I have: (which works fine)
/invoices
But say I want:
/invoices/status/unpaid
How is this achievable?
To see the basics of what I am doing check:
http://laravel.com/docs/controllers#resource-controllers
Resource controllers tie you into a specific URLs, such as:
GET|POST /invoices
GET|PUT /invoices/{$id}
GET /invoices/create
and so on as documented.
Since, by convention, GET /invoices is used to list all invoices, you may want to add some filtering on that:
/invoices?status=unpaid - which you can then use in code
<?php
class InvoiceController extends BaseController {
public function index()
{
$status = Input::get('status');
// Continue with logic, pagination, etc
}
}
If you don't want to use filtering via a query string, in your case, you may be able to do something like:
// routes.php
Route::group(array('prefix' => 'invoice'), function()
{
Route::get('status/unpaid', 'InvoiceController#filter');
});
Route::resource('invoice', 'InvoiceController');
That might work as the order routes are created matter. The first route that matches will be the one used to fulfill the request.

Hide Codeigniter controller name from URL with same routes

i'm just getting started at codeigniter, i want to hide controller name from URL with same routes setup.
i have 3 controllers which are students, staff, teachers having same function called home, this won't work obviously
$route['home'] = 'students/home';
$route['home'] = 'staff/home';
is there any way to accomplish this? i have session data using codeigniter session class containing user type so i tried something like this
session_start()
$route['home'] = $_SESSION['user_type'].'/home';
but i cant get the session data, maybe its using codeigniter session class?? so, how can i get the data? or is there other solution?
Perhaps you should write a common controller and disperse by your second URI parameter:
home/students or home/staff
$route['home/:any'] = "home";
and home controller's index method:
public function index()
{
$type = $this->uri->segment(2);
switch($type){
case "student":
$this->student();
break;
case "staff":
$this->staff();
break;
default:
$this->some_other_method();
break;
}
}
Obviously you would create a student and staff method and handle things differently if need be.
A side note - why do you want to conceal the controller's name? It's not like that's a security hole or anything.

_remap or URI Routing in codeigniter

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';

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