Wednesday, March 28, 2012

Codeigniter + HMVC + Namespaces (part 2)

Now I'm going to continue with CI+NAMESPACES+HMVC transformation. (See part 1)

Codeigniter + Namespaces + HMVC

Working with namespaces in hmvc is same that part 1. The diference is how we load a namespaced module:

namespace controllers\blog;

class user extends \MX_Controller {
  public function get_comments($id_user){
     /* Code */

     $module = $this->load->module('namespace\modulename/classname');
     $module->method($x, $y);

     // OR [3]
     \Modules::run('namespace\modulename/classname/method', $x, $y);
$_ns = __NAMESPACE__;

How to load a module
  1. Load module into a variable. The format is namespace\[backslash]modulename/[slash]classname
  2. Call the module method
  3. Run module method statically
Download HMVC extension patch

Download HMVC module example

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.