Creating a filter from parent class? - php

I'm using CodeIgniter and I want to create some sort of filter to know when a user may/may not access a current controller
If anyone has any idea how to implement this in a different manner, great, but what I was thinking (and trying to do) is the following:
CI_Controller - which is the basic CodeIgniter controller class
MY_Controller - the basic controller which I use which extends CI_Controller
[Controller] - any "physical" controller
what i've tried to do is:
MY_Controller.php
class MY_Controller extends CI_Controller{
private static $namespace = null;
private static $permission = array('site', 'settings');
public function __construct(){
if ((!isset($_SESSION['user'])) && (in_array(__CLASS__, $permission))){
throw new Exception('Unauthorized');
}
parent::__construct();
}
}
obviously, this doesn't work as CLASS will always be that of MY_Controller and not that of the child object... and NAMESPACE doesn't work aswell.
Anyone has any idea? because Id really hate to start putting this snippet of code in every other class, and I'll prolly need the filtering later for some more elaborate things...

As there's no answer so far, maybe this suggestion might help. It's a different approach, though, that uses the Modular Extensions - HMVC ...
Like this you can have a module "login" with a controller that holds some methods to log a user in, to check session status and to log a user out (and the like).
In each other module you can now load the module login and check for the status and redirect if needed ...
There's a tutorial HMVC: an Introduction and Application I followed on nettuts that shows how to do the CodeIgniter From Scratch: Day 6 – Login in that way. Maybe that helps. I had some difficulties as it's with an old codeigniter version. So maybe this thread helps.
It's not how you're trying to do things, but maybe it helps!

I did not try it but what I saw in this forum might be working for you. The predicted code is:
class MY_Controller extends Controller{
private static $permission = array('site', 'settings');
public function __construct(){
if ((!isset($_SESSION['user'])) && (in_array(__CLASS__, $permission))){
throw new Exception('Unauthorized');
}
parent::Controller();
}
}
But then you'd need to use
class My_controller extends MY_Controller
instead of
class My_controller extends Controller

I solved it in the following manner... simply in the constructor, I defined the current class
class MY_Controller extends CI_Controller{
private static $permission = array('site', 'settings');
public function __construct($currentController = __CLASS__){
if ((!isset($_SESSION['user'])) && (in_array($currentController , $permission))){
throw new Exception('Unauthorized');
}
parent::Controller();
}
}
when calling the physical controller, we simply write as follows
class PhysicalController extends MY_Controller{
public function __construct(){
parent::__construct(__CLASS__);
}
}

Related

Route in codeigniter3

I am learning codeigniter 3
In my config.php:
$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/ci3x/admin/';
In my routes.php:
$route['customer'] = 'customer/index';
In controllers/customer.php:
class Customer extends MY_Controller{
function index(){
// some code here
}
}
When I type: http://localhost/ci3x/admin/customer on brower, it back error 404.
I have no clue to fix, please help me to solve it.
Many thanks
As you are extending a Class and that class does have a constructor, your class needs a constructor that also calls the constructor of the extended class.
Else things won't get up and running correctly.
class Customer extends MY_Controller{
public function __construct() {
parent::__construct(); // Call the MY_Controller constructor
}
function index(){
// some code here
}
}
The same goes for your MY_Controller constructor as it will need to call CI_Controller constructor... It ripples down and everything gets initialised correctly (in simplistic terms) .
Note:
Be careful with your controller and method files names. If you read the user guide it will say that the file names for controllers and methods should start with a capital letter.
So your controllers/customer.php should be controllers/Customer.php. If you are running on Windows it won't care. If you are running on Linux it will definitely matter.

Extending CI_Controller

All I'm trying to do is something fairly simple :
Create a class (let's say brandNewClass - NOT MY_Controller) which extends CI_Controller
Create other controllers which extend brandNewClass
E.g.
class brandNewClass extends CI_Controller {
public function index()
{
}
public function info()
{
}
}
used like (in a file under /controllers) :
<?php
class newController extends brandNewClass
{
}
?>
The thing is, although it works when I'm copying the file under /application/core and naming it as MY_Controller, when I change the name to something more... self-explanatory, it doesn't.
Fatal error: Class 'brandNewClass' not found in .... on line ..
I've even tried using the __autoload function mentioned here, but without any luck.
Any ideas?
Have a look at this excellent tutorial - I hope it helps
http://codeigniter.tv/a-10/Extending-the-core-MY_Controller-and-beyond
The autoloader doesn't automaticly include other controllers. you will have to include it manually like this:
if (!defined('BASEPATH'))exit('No direct script access allowed');
include_once(APPPATH . 'controllers/brandnewclass.php');
If you want to create a custom base controller and make other controllers extend there, you can do it in following ways:
Create MY_Controller extending CI_Controller in application/core/ folder and make other controllers extend MY_Controller as MY_Controller will be autoloaded from core (This I guess you already know but want other alternatives.
Create MY_Controller in application/core/. Then create other level of Controllers that can primarily be Admin_Controller and Frontend_Controller. Now, one of these controllers will make base for your actual used controllers.
e.g. in application/core/MY_Controller.php
class MY_Controller extends CI_Controller {
public function __construct(){
parent::__construct();
}
}
Then Admin and Frontend controllers will be created in application/libraries/ and will extend MY_Controller like
class Admin_Controller extends MY_Controller {
public function __construct(){
parent::__construct();
}
}
Now, Any controller can extend one of these 2 controllers but for doing that you will have to autoload them. For autoloading in this case there can be a confusion because setting autoload['libraries'] in config/autoload.php will not work . That autoload works inside a controller but here we need to autoload before that i.e. in the class declaration. Will need to set this code in config/config.php
function __autoload($class)
{
$path = array('libraries');
if(strpos($class, 'CI_') !== 0) {
foreach($path as $dir) {
$file = APPPATH.$dir.'/'.strtolower($class).'.php';
if (file_exists($file) && is_file($file))
#include_once($file);
}
}
}
Now you can create your own controller
class newController extends Admin_Controller
{
}
This is the most suggested method making your structure quite clean and effective. May take some effort in understanding for the first time but is definitely worth it.
Third method is just a tweak of the second one, just based on the condition you mentioned of not using MY_Controller
You can make Admin_Controller or Frontend_Controller extend CI_Controller directly and not extend MY_Controller
That may just lead to some duplicity of code in both these controllers if that may be the case
http://philsturgeon.co.uk/blog/2010/02/CodeIgniter-base-Classes-Keeping-it-DRY
I suspect you're trying something similar?
There's an autoload function that you can add to the config file so that you needen't require_once() the class all the time.
You should declare the class as abstract, since it shouldn't be instantiated directly.
You'll need to modify the CodeIgniter autoloader configuration file and add your class to it, or change the actual autoloader.
You really should consider not using CodeIgniter :)

Extending The Controller Class in CodeIgniter

I have class MY_Controller extends CI_Controller and common logic for big profile section, so I'va tried to create class Profile extends MY_Controller with common logic for profile section and all class related to this section should extends this Profile class as I understand right, but when I tried to create class Index extends Profile I recieve an error:
Fatal error: Class 'Profile' not found
CodeIgniter tries to find this class in index.php which I am running.
Where is my mistake? Or maybe there is anoter better way to mark out common logic?
I take it you have put your MY_Controller in /application/core, and set the prefix in the config.
I would be careful about using index as a class name though. As a function/method in Codeigniter it has a dedicated behaviour.
If you then want to extend that controller you need to put the classes in the same file.
E.g. In /application core
/* start of php file */
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
}
...
}
class another_controller extends MY_Controller {
public function __construct() {
parent::__construct();
}
...
}
/* end of php file */
In /application/controllers
class foo extends MY_Controller {
public function __construct() {
parent::__construct();
}
...
}
or
class bar extends another_controller {
public function __construct() {
parent::__construct();
}
...
}
I found this page on Google because I had the same problem. I didn't like the answers listed here so I created my own solution.
1) Place your parent class in the core folder.
2) Place an include statement at the beginning of all classes that include the parent class.
So a typical controller might look like this:
<?php
require_once APPPATH . 'core/Your_Base_Class.php';
// must use require_once instead of include or you will get an error when loading 404 pages
class NormalController extends Your_Base_Class
{
public function __construct()
{
parent::__construct();
// authentication/permissions code, or whatever you want to put here
}
// your methods go here
}
The reason I like this solution is, the whole point of creating a parent class is to cut down on code repetition. So I don't like the other answer that suggested copy/pasting the parent class into all of your controller classes.
It is possible with Codeigniter 3. Just including the parent file is enough.
require_once(APPPATH."controllers/MyParentController.php");
class MyChildController extends MyParentController {
...
All classes you are extending should live in application/CORE directory so in your case both My_Controller and Profile should live there. All "end point" controllers will live in application/controllers folder
UPDATE
I stand corrected. Extended classes should live in the same file. #Rooneyl's answer shows how to implement
After some struggle with version 3 and this issue I decided this was not a bad solution...
require_once BASEPATH.'core/Controller.php';
require_once APPPATH.'core/MYCI_Controller.php';
to add this second line where the first exists in the system/core/CodeIgniter.php
[If it's not too late, I recommend strongly against php and/or CodeIgniter.]

OOP PHP Codeigniter Controller Hierarchy

I'm having a litle problems with my concepts of OOP. I'll try to explain the best I can.
I have this class
class Application_controller extends CI_Controller{
public function addItem(){
"some code to add the item to the database (working)";
}
}
And I have another class, both controllers:
require_once 'application_controller.php';
class Contact extends Application_controller{
public function __construct(){
parent::__construct("variables needed");
}
}
And in the View add of the contact I added the following action contact/addItem.
Ok, now here's what I know about OOP in general.
Isn't the method addItem supposed to be part of the Contact class because its extends Application_controller?
I'm asking because when I submit the form I get no action, and when I add the method addItem in the class Contact overriding the parent one it works.
The reason you get no action is that codeigniter doesn't find a method addItem in your Contact class (update: this is probably due to the way CodeIgniter routing works). The solution would be to make addItem a generic method in a Model that stores data in a table, move it to a Model, and load the model in your controller.
Create application/models/writeModel.php
class writeModel extends CI_Model{
function addItem(){
// code here
}
}
In your controller:
class Contact extends Controller{
function __controller(){
parent::Controller();
$this->load->model('writeModel');
}
function somefunction(){
$this->writeModel->addItem(); // call the method here
}
}
Reference: CodeIgniter Models
The problem here (other then the several syntax errors in the OP) is likely to be that "Contact" can not extend "Application_controller" because it does not know it exists. If we setup a test like this:
/controllers/Test.php
class Test extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
echo 'test';
}
}
/controllers/TestTwo.php
require_once("Test.php");
class TestTwo extends Test
{
function __construct()
{
parent::__construct();
}
function index()
{
parent::index();
echo ' and test two';
}
}
We will get the desired output of "test and test two" by navigating to appurl/TestTwo/. This is because TestTwo knows of Test. Removing the require(); line from TestTwo.php will break the relation.
Removing the index() function from TestTwo will then result in only "test" being output by navigating to appurl/TestTwo/.
I found an answer to some similar question on the Codeigniter forums. It says this
your ShopDownloads will inherit (methods,properties etc etc) from the Shop controller. and as said in the video tutorial, u must inherit your class from the controller class so that it can inherit all the properties and methods codeigniter provides for u.
Sohaib,
The link for the post is http://codeigniter.com/forums/viewthread/102718/#518120
I don't know how but this is working today. It was probably the server. Just needed a restart.
Its Solved, just by start the server today and start developing LOL. Thanks for youre time guys.
Regards,
Elkas

Codeigniter extending extended MY_Controller

I have strictly followed the how-to article by Phil Sturgeon, to extend the base controller. But I get still some errors.
My 3 classes:
// application/libraries/MY_Controller.php
class MY_Controller extends Controller{
public function __construct(){
parent::__construct();
}
}
// application/libraries/Public_Controller.php
class Public_Controller extends MY_Controller{
public function __construct(){
parent::__construct();
}
}
// application/controllers/user.php
class User extends Public_Controller{
public function __construct(){
parent::__construct();
}
}
Fatal error: Class 'Public_Controller' not found in /srv/www/xxx/application/controllers/user.php on line 2
Curious is that the following snippet is working, if I directly extends from MY_Controller:
// application/controllers/user.php
class User extends MY_Controller{
public function __construct(){
parent::__construct();
}
}
I have loaded the controllers via __autoload() or manually. The controllers are loaded succesfully.
CI-Version: 1.7.3
You need to require the Public Controller in your MY_Controller
// application/libraries/MY_Controller.php
class MY_Controller extends Controller{
public function __construct(){
parent::__construct();
}
}
require(APPPATH.'libraries/Public_Controller.php');
You get the error because Public_Controller was never loaded. Doing this would allow you to extend from Public_Controller
I like what you are doing because I do that all the time.
You can do this also in your MY_Controller when you want to create an Admin_Controller
// application/libraries/MY_Controller.php
class MY_Controller extends Controller{
public function __construct(){
parent::__construct();
}
}
require(APPPATH.'libraries/Public_Controller.php'); // contains some logic applicable only to `public` controllers
require(APPPATH.'libraries/Admin_Controller.php'); // contains some logic applicable only to `admin` controllers
You should place Public_controller in with MY_Controller inside MY_Controller.php
// application/libraries/MY_Controller.php
class MY_Controller extends Controller{
public function __construct(){
parent::__construct();
}
}
class Public_Controller extends MY_Controller{
public function __construct(){
parent::__construct();
}
}
I use __construct everywhere and it works fine I recently wrote up an article on how to do this in relation to wrapping your auth logic into your extended controllers. It's about half way down when I start discussing constructing your controllers.
Problem was solved here: http://devcrap.net/pl/2011/09/04/codeigniter-dziedziczenie-z-my_controller-extends-my_controller/. In polish but code is good :]
I had problem like this,After some search I found error was made myself,Because my controller class name was MY_Controller but file name was My_Controller[Case not matching].
Note:- In localhost I didnt have any error.
In extended controller I Use
class Home extends MY_Controller{
function __construct() {
parent::__construct();
}
}
even I got the error.
After changing my file name to MY_Controller it started to work well.
I have a custom controller class called MY_Controller it extends CI_Controller and it works fine. It is located at application/core and it has custom functions lo load views in my site.
I use an abstract class My_app_controller that extends MY_Controller for my_app specific behabior, I want every controller in my_app to extend this abstract class. (I use diferent apps in the site, so some apps will extend My_app_controller and other apps will extend My_other_apps_controllers)
But when I try to extend My_app_controller from any controller in my application, "Main_app_controller extends My_app_controller" generates a Class 'My_app_controller' not found exception.
I found two solutions:
use include_once in Main_app_controller.php file.
include_once APPPATH.'controllers/path/to/My_app_controler.php';
break the "one class per file" rule of code igniter and define my My_app_controller just in the same file MY_Controller is (under application/core).
Manual says:
Use separate files for each class, unless the classes are closely
related
Well... they are.
Anyway, I prefered to use the include_once solution as I think it is better to have one file per class and My_app_controller is located under application/controllers/my_app folder. (so application/controllers/other_apps will exist)

Categories