Search code examples
phpcodeigniterinternationalizationextendhmvc

PHP Extend Class Conditionally? (CodeIgniter 3 Use Case)


I'm using the following scenario, but this doesn't necessarily pertain only to CodeIgniter.

HMVC: https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc

Internationalization (i18n): https://github.com/waqleh/codeigniter-language-in-url-internationalization

Both HMVC & i18n work by extending CI_Config (and related CI_ classes).

To get i18n working alongside HMVC, I first have to require the appropriate HMVC file and then further extend that class.

So for example, CI_Config is extended by HMVC MX_Config and then further required & extended by i18n MY_Config.

But now i18n only works if HMVC is already in place.

What if HMVC is absent (no MX_Config and related)?

I want i18n to work both with/without HMVC.

Is there a way to conditionally require & extend one class or another? Or rather, extend CI_Config (and related) twice without collision? Or is there another way to accomplish what I want?

HMVC MX_Config partial:

/**
 * HMVC
 */
class MX_Config extends CI_Config
{

i18n MY_Config partial:

/* load HMVC's MX_Config class */
require APPPATH . "third_party/MX/Config.php";

/**
 * Language
 */
class MY_Config extends MX_Config
{

Solution

  • localheinz's answer is valid but does not take into account:

    CodeIgniter loads core files CI_ & MY_ before HMVC MX_ . So there's no way to have MY_ check if an MX_ is declared.

    Nor do I want to edit core CI_ files as they are not meant to be modified.

    The working solution:

    Note: The same logic below can be applied to other MY_ classes.

    MY_Config partial:

    /* load HMVC's MX_Config class */
    if ( file_exists(APPPATH . "third_party/MX/Config.php") ) {
        require APPPATH . "third_party/MX/Config.php";
    /* otherwise declare MX_Config class */
    } else {
        class MX_Config extends CI_Config {}
    }
    
    
    /**
     * Language
     */
    class MY_Config extends MX_Config
    {