连接静态和非静态方法

时间:2013-05-23 11:52:31

标签: php codeigniter interface static dependency-injection

好的,我的问题是尝试连接静态和非静态方法,两者都是一个例子。

问候。

示例:

Codeigniter AR(非静态)和

PHP-ActiveRecord的(静态)

接口

interface userRepoInterface
{

    public  function get($id=null); //should be static or non-static

}

PHP-ActiveRecord的

class User extends ActiveRecord\Model implements userRepoInterface
{

    public static function get ( $id = null )
    {
        try
        {
            if(is_null($id)){
                $user = self::all();
            }
            elseif(is_int($id)){
                $user = self::find($id);
            }

        }catch(ActiveRecord\RecordNotFound $e)
        {
            log_message('error', $e->getMessage());
            return false;
        }

        return ($user) ?:$user;
    }
}

Codeigniter AR

class CIUser extends CI_Model implements userRepoInterface
{

    public function __construct ()
    {
        parent::__construct () ;
    }

    public function get ( $id = null )
    {
        if ( is_null ( $id ) ) {
             $user = $this->db->get('users');
        }
        elseif ( is_int($id) ) {
            $user = $this->db->get_where('users', array('id'=> $id));
        }

        return ($user->num_rows() > 0) ? $user->result() : false;
    }

}

-

TestCase Library(Authenticate)

class Authenticate
{

    protected $userRepository;


    public function __construct (  userRepoInterface $userRepository )
    {
        $this->userRepository = $userRepository;
        print'<pre>';
        print_r($this->userRepository->get());
    }

    public function __get ( $name )
    {
        $instance =&get_instance();
        return $instance->$name;
    }
}

-

TestCase控制器

public function index ()
    {

        $model1 = new \User; //this is static
        $model2 = $this->load->model('CIUser'); //this is non-static

        $this->load->library('Authenticate', $model1);

    }

1 个答案:

答案 0 :(得分:1)

在这种情况下,我看到的唯一合理的解决方案是在接口中使其静态,在类似于使用实例的类中:

public static function get ( $id = null )
{
    $instance = new static;

    if ( is_null ( $id ) ) {
         $user = $instance->db->get('users');
    }
    elseif ( is_int($id) ) {
        $user = $instance->db->get_where('users', array('id'=> $id));
    }

    return ($user->num_rows() > 0) ? $user->result() : false;
}