在动态加载时使用类

时间:2018-03-06 05:25:13

标签: php

我一直潜伏在CI的Loader类中,我对它如何加载模型/库等感兴趣。

例如:

//Mode class person
$this->load->model('person');

可立即使用:

$this->person->method();

有人可以分享一些关于如何做这样的事情的代码吗?我尽可能不想使用类似的东西:

$Person = $this->mycustomloader->mycustommodel->('person);

但:

$this->mycustomloader->mycustommodel('person');
$this->person->mycustommethod();

提前致谢!

1 个答案:

答案 0 :(得分:0)

它在CI的情况下是如何完全依赖于通过引用传递东西(单例),因此调用$this->load->model('person')会调用person模型并将其分配回控制器。

通过查看GitHub上的项目来源,您可以确切了解其完成情况。

但简而言之:

<?php
// https://github.com/bcit-ci/CodeIgniter/blob/635256265a38e655c00f4415d5f09700f28c5805/system/core/Common.php#L140
function load_class($class) {
    return (new $class());
}

// https://github.com/bcit-ci/CodeIgniter/blob/b862664f2ce2d20382b9af5bfa4dd036f5755409/system/core/CodeIgniter.php#L316
function &get_instance() {
    return CI_Controller::get_instance();
}

// https://github.com/bcit-ci/CodeIgniter/blob/b862664f2ce2d20382b9af5bfa4dd036f5755409/system/core/Loader.php#L359
class CI_Loader
{
    public function model($model, $name = '', $db_conn = FALSE)
    {
        $class = $model.'Model';
        $CI =& get_instance();
        $CI->{$model} = new $class;
    }
}

// https://github.com/bcit-ci/CodeIgniter/blob/b862664f2ce2d20382b9af5bfa4dd036f5755409/system/core/Controller.php#L52
class CI_Controller {
    private static $instance;

    public function __construct()
    {
        self::$instance =& $this;
        $this->load =& load_class('CI_Loader');
    }

    /**
     * Get the CI singleton
     *
     * @static
     * @return  object
     */
    public static function &get_instance()
    {
        return self::$instance;
    }
}

// your models
class fooModel {
    public $foo;
}

class barModel {
    public $bar;
}

// your controller
class Controller extends CI_Controller {

    public function indexAction()
    {
        $this->load->model('foo');
        $this->load->model('bar');
    }
}

// instance container
$app = (new class{});
$app->controller = new Controller();

// loaded by router
$app->controller->indexAction();

print_r($app);

结果(忽略错误):

class@anonymous Object
(
    [controller] => Controller Object
        (
            [load] => Loader Object
                (
                )

            [foo] => fooModel Object
                (
                    [foo] => 
                )

            [bar] => barModel Object
                (
                    [bar] => 
                )

        )

)

https://3v4l.org/fPCK3