Tuesday, March 06, 2012

Codeigniter + HMVC + Namespaces (part 1)

Codeigniter 2.1.0 is PHP4 compatible, so it can't work with namespaces.

I work with HMVC extension, and I see that working with it and without namespaces it's a little clumsy (for example class collisions) so, I decided to modify Codeigniter and hmvc extension to work with namespaces for controllers.

Both solutions are independents. First I'm going to explain how to make it possible in Codeigniter only.

Codeigniter + Namespaces

namespace controllers\blog //[1]

class user extends \CI_Controller { //[3]
  public function get_comments($id_user){
     // Code  
  }
}
$_ns = __NAMESPACE__; //[2]

What is new here?
  1. You can see namespaces declaration, obviously [1]
  2. The new (required) variable. It is used by patch [2]
  3. As Codeigniter doesn't work with namespaces we must use a global namespace [3]
Anything else?

No! How easy!

Well, one more thing is required. Replace the system/core/Codeigniter.php file with the patch.
If you are afraid to do it, I have modified 2 lines only.

No comments: