1

我正在寻找帮助识别这种设计模式并学习它使用的“典型”词汇:

我正在开发一个 PHP 项目,并且我创建了一个薄 ORM 层,用于将通用对象保存到数据库中和从数据库中保存。有两个类可以完成这项工作:

  • “my_object”基本上是各种数据的容器。创建此对象后,可以将自身保存到数据库中。
  • “my_object_manager”用于管理一组对象,例如,如果您想检索其中的许多对象并遍历它们。

作为一个简化的示例,您可以执行以下操作:

$post = new my_object('post');
$post->title = 'foo';
$post->body = 'bar';
$post->author = 'baz';

...如果您想加载一堆帖子,您可以执行以下操作:

$posts = new my_object_manager('post');
$somePosts = $posts->getBy('author','baz');
foreach( $somePosts as $aPost ) {
    ...loop stuff here...
}

所以,我的问题是:在“my_object_manager”的类定义中,我需要存储一个属性来标识正在管理的对象类型。它看起来像这样:

class my_object_manager {
    protected $theKindOfObjectThatThisManages;

    function __construct($whatToManage) {
        $this->theKindOfObjectThisManages = $whatToManage;
    }
}

现在,请原谅我不知道这种基本的东西,但我是自学的,编程词汇量非常有限。我确信这种设计模式很常见,但在我的一生中,我一直无法弄清楚它叫什么。

我正在尝试编写其他程序员可以阅读和理解的代码,所以,我真正的问题是,如果您正在阅读此代码,您希望“$theKindOfObjectThatThisManages”被调用什么?这个程序设计模式叫什么,如果你想让其他程序员知道它在做什么,你怎么称呼这种对象?

最后,问题编辑器弹出并告诉我这个问题看起来很主观,可能会被关闭。我希望这个问题实际上对 Stack Overflow 来说是可以的——但如果不是,我在哪里可以问这个问题并得到答案?

谢谢!

4

2 回答 2

1

对于您的代码示例,我会使用

class my_object_manager {
    protected $my_object_type;

    function __construct($whatToManage) {
        $this->my_object_type = $whatToManage;
    }
}

现在,您似乎正在密切关注Active Record 模式,其中存在许多实现 ,您可以去看看他们在实践中是如何做到的 :)

通常,您不提供对 _manager() 对象的访问权限,而是让 my_object() 继承自它。所以,你会有类似的东西

$posts = new Posts(); //Where Posts() extends my_object_manager
$somePosts = $posts->getBy('author','baz');
foreach( $somePosts as $aPost ) {
    ...loop stuff here...
}
于 2010-09-23T20:59:41.917 回答
1

查看:

http://en.wikipedia.org/wiki/Design_pattern_(computer_science)

您的对象管理器的设计,取决于它的复杂程度,可能属于几种模式。例如:

Composite: Maybe your object manager allows you to run updates on multiple objects at once (typical database scenario) using the same interface. You can alter individual objects in the same way you'd alter collections.

Facade: If your object manager provides methods to combine various parts of your system into a single, easier to use interface then it's using the Facade pattern. For example, maybe your object manager creates a 'user' object and automatically generates their first 'post' via a single API call. Perhaps you could have used create() functions on the post and user objects to do this yourself, but the Facade pattern combines them (and perhaps helps to deal with concurrency issues as well) into an easier API since these operations are commonly called together.

Mediator/Observer: Your object manager might be responsible for observing changes to objects and handling the "mediation" between them. Your object manager might provide a method for commenting on a post. But when this method is called, the author of the post might need to be notified via email. So your object manager could be responsible for communicating between the relevant objects and notifying a listening email service by sending an event or similar message.

于 2010-09-23T21:35:34.397 回答