__get() 和 __set() 的最佳实践 [英] Best Practices for __get() and __set()

查看:47
本文介绍了__get() 和 __set() 的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

源于这个 问题 关于使用 __get()__set() 访问私有变量,我想获得有关它们通常如何使用的输入.我想知道何时何地是使用重载函数的最佳时机,以及您在何处使用过重载函数(如果有的话).

Stemming from this question on using __get() and __set() to access private variables, I'd like to get the input on how they are used in general. I am wondering when or where would be the best time to use a overloading function, and where you have used one (if you have).

为了清楚起见,我们正在谈论这些功能:http://us2.php.net/manual/en/language.oop5.magic.php

Just to be clear, we are talking about these functions: http://us2.php.net/manual/en/language.oop5.magic.php

推荐答案

Lazy Models Getters(使用 __get())

我不记得在我的应用程序中经常使用 PHP 的魔法方法,但我记得在一种情况下 __get() 非常有用.

过去我在 CakePHP 框架中开发一个应用程序,它有很多模型,并且在特定控制器中使用的所有模型都被初始化,即使方法只使用其中的一两个(这就是 Cake 的工作方式).所以我决定把它改成懒惰模型到懒惰(第一次使用时加载模型).

Back in the days I was developing an application in CakePHP framework that had a lot of models and all models that are used in specific controller were initialized even if method make use only of one or two of them (that's how Cake was working). So I decided to change that to lazy models to lazy (loading models when they are used for the first time).

我所做的只是添加了一个非常简单的 __get() 函数,该函数查找具有特定名称的模型并加载它.就像 3-4 行代码.我在 AppController 中定义了它(所有 CakePHP 类都派生自该控制器),突然我的应用程序提高了速度并使用了更少的内存.

All I did is I added a very simple __get() function that looked for a model with specific name and loaded it. It was like 3-4 lines of code. I defined that in AppController (all CakePHP classes derives from that controller) and suddenly my app gained speed and used lower memory.

我后来更进一步,并以相同的方式加载延迟组件.

I took it further later on and also made lazy components loading in the same way.

同样来自 CakePHP 的另一个很好的例子是 Cake 搜索模型的方式.基本上你有两种方法: find()findAll() 在每个模型中,但你也可以使用方法 findBy()findAllBy().

Another good example, also from CakePHP, is how Cake searches on models. Basically you have two methods for that: find() and findAll() in every model, but you can also search using methods findBy<FieldName>() and findAllBy<FieldName>().

例如,如果您有数据库表

In example if you have db table

notes(id, date, title, body)

并为此创建 Cake 模型.可以使用findById()findByTitle()等方法.您只需要 CamelCase db 字段,并且可以更快地搜索任何字段.

And create Cake model for that. You can use methods such as findById(), findByTitle() and so on. You need only CamelCase db field and you can do a search on any field much quicker.

Cake 通过使用 __call() 魔术方法来实现.如果您尝试执行一个不存在的方法,然后它只运行 find()findAll() 和从方法名称动态创建的条件,则会调用此方法和参数.这实施起来非常简单,并且可以为您带来很多好处.

Cake does it by using __call() magic method. This method is called if you are trying to execute a method that doesn't exists and then it just runs find() or findAll() with conditions dynamically created from method name and parameters. This is very simple to implement and can give you really a lot of benefits.

这篇关于__get() 和 __set() 的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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