0

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

问候。

例子:

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;
    }

}

-

测试用例库(认证)

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;
    }
}

-

测试用例控制器

public function index ()
    {

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

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

    }
4

1 回答 1

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;
}
于 2013-05-23T12:18:46.143 回答