PHP中的类方法访问控制 [英] Class methods access control in PHP

查看:53
本文介绍了PHP中的类方法访问控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在不同上下文(我系统中的API)中使用对象方法时,我需要组织对对象方法的某种访问控制.这是代码示例:

I need to organize some kind of access control to object methods when it is used in different contexts (API's in my system). Here is code example:

    class A
    {
      public function doA(){}
      public function doB(){}
    }

    class APIAClient
    {
      public function getA()
      {
        return new A();
      }
    }

    class APIBClient {
      public function getA()
      {
        return new A();
      }
    }

在APIAClient中,对象A应该同时具有doA()和doB()方法,但在APIBClient中,则不应具有doB()方法.

In APIAClient object A should have both methods doA() and doB(), but in APIBClient should not have doB() method.

目前,我已经实现了APIBClientAProxy(由APIBCleint-> getA()返回)

For now I've implemented APIBClientAProxy (which is returned by APIBCleint->getA())

   class APIBClientAProxy
   {
     private $a = new A;
     public function doA()
     {
       $this->a->doA()
     }
   }

但是也许有一种更好的模式可以解决我的问题,而无需为每个上下文(即API)使用额外的代理对象.我正在考虑魔术__call方法以及在特定上下文中允许使用的方法的列表,但是魔术调用很难编写文档,而文档是我应用程序中的重点(应该很好地记录API)

But may be there is a better pattern for solving my problem, without using a additional proxy object for every context (i.e. API). I'm thinking about magic __call method with list of allowed methods in particular context, but magic calls is hard do document and documentation is the big point in my app (API's should be documented well)

谢谢!

推荐答案

除了继承之外,您还可以通过特征使用组合(PHP 5.4中引入).

Instead of inheritance you can use composition through traits (introduced in PHP 5.4).

首先定义特征

trait A {
  public function doA() {
    // do something here
  }
}

trait B {
  public function doB() {
    // do something here
  }
}

然后在类声明中使用这些特征

then use those traits in your class declaration

class APIAClient {
  use A, B

}

class APIBClient {
  use A
}

这篇关于PHP中的类方法访问控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆