Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter Custom Libraries and Namespaces

I have been creating custom libraries for a project that i've been porting over into the CI framework and I ran into an issue where certain classes have identical names.

To circumvent this issue, I tried implementing namespaces to no avail. I've been doing research and I know in the past this may not have been possible but with the newer version of PHP, I was wondering if there was a way to do this or if I was doing it correctly.

CI Version: 2.1.4 PHP Version: 5.4.12

Here is a demo of my setup:

application/libraries/class1.php

<?

class class1{
   public function __construct()
    {
        $CI =& get_instance();

        $CI->load->library('foo/class2.php');
    }
}
?>

application/libraries/foo/class2.php

<?

namespace foo

class class2{

    function bar(){

    }

} 

?>

When I run my CI application, I will get the following error:

Non-existent class: class2

Thanks for any help.

like image 773
ssj16 Avatar asked Mar 14 '14 16:03

ssj16


3 Answers

From what I've found, if the library file doesn't have

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

as the first line of code it won't load the library.

But then the namespace declaration needs to be above that.

CodeIgniter was written for PHP4 whereas namespace is PHP5.

There's more information in this thread: Namespace in PHP CodeIgniter Framework

like image 195
david_nash Avatar answered Oct 17 '22 16:10

david_nash


Codeigniter does not support namespaces in 2.x and 3.x, what I would usually do especially with 3rd party libraries is load them in manually. Using your example, I would do:

// you can still manually load in libraries like this
require_once(APPPATH.'libraries/foo/class2.php');

class class1 {

   public function __construct()
    {
        $CI =& get_instance();

        // instantiate the class2 and make it available for all of class1 methods
        $this->class2 = new foo/class2();
    }

}

Just because it's a framework doesn't prevent you from using core php functionality, most people forget that you can still do normal php methods to achieve the same results.

like image 2
tmarois Avatar answered Oct 17 '22 15:10

tmarois


This issue arose in a personal project while attempting to use some third-party libraries.

To get around it (without modifying the source files), I made a "bootstrap" class that loaded and extended the core library:

<?php

require_once(APPPATH.'libraries/foo/class2.php');

class class2 extends foo\class2 {}

This "bootstrap" class can then be loaded and used as if it were the extended one:

$this->load->library("class2");

$this->class2->bar(); // same as foo\class2->bar();
like image 2
AlbinoDrought Avatar answered Oct 17 '22 16:10

AlbinoDrought