douzha6055 2017-08-14 01:22
浏览 62
已采纳

PHP有条件地扩展类? (CodeIgniter 3使用案例)

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
{
  • 写回答

2条回答 默认 最新

  • dprq18175 2017-08-14 15:43
    关注

    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
    {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?