接口静态和非静态方法



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

致意。

例子:

Codeigniter AR(非静态)和

php-activeRecord(静态)

界面
interface userRepoInterface
{
    public  function get($id=null); //should be static or non-static
}

Php-ActiveRecord

class User extends ActiveRecordModel 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(ActiveRecordRecordNotFound $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库(验证)

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

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

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

最新更新