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条)

报告相同问题?

悬赏问题

  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗