Php函数名与类匹配 [英] Php function names paired with classes

查看:71
本文介绍了Php函数名与类匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将函数名与类匹配是否被认为是不好的做法?



例如,在kohana中,我可以执行以下操作。

 函数模型($ a,$ b){
返回新模型($ a,$ b);
}

然后我可以删除所有引用新的,不必做出$ temp变量,并且没有工厂混乱。

  $ temp = new Model('book'); $('title','=','name') - > find(); 
$ book = $ temp->



 <$ ('title','=','name'); 

 <$ ('title','=','name'); 

据我所知,全球污染很糟糕,起初读起来有点模糊,但它有好处。



我的意思是,如果有人定义了一个与类无关的函数,那么为什么不使用函数?
$ b

例如:

  $ book = new Model('book'); 
//看起来如此接近上面,它很可怕
$ book = Model('book');

其他优点或缺点

解决方案

我偶尔会这样做。它有时可以使代码更具可读性。



这叫做工厂程序。但是,如果它们不那么浅薄,这是最有意义的。例如,如果取决于参数,这种方法可能会返回不同的对象(替代占位符/存根对象):

  class User {.. 。

函数User($ id){
return($ id< 0)?新的PlaceholderUser():新用户($ id);
} //或其他*存根对象*来支持应用程序流

你可以使用它来获得更好的外观。它基本上比普通的静态工厂方法更简洁。但是我会为你真正使用很多的对象保留这种包装函数。使用每个现有类的包装器调用来填充函数范围是没有意义的。



这里常见的批评是:没有经验的开发人员很容易被对象弄糊涂没有新的的实例化。 (不知道这是否正确,但在这种情况下通常会这样说。)


Is it considered bad practice to pair function names with classes?

For example in kohana I could do the following.

function Model($a,$b){
    return new Model($a,$b);
}

Then I could drop all references to new, wouldn't have to make a $temp variable, and no factory clutter.

$temp = new Model('book');
$book=$temp->where('title','=','name')->find();

Or

$book = Model::factory('book')->where('title','=','name');

To

$book = Model('book')->where('title','=','name');

I understand global pollution is bad and it is slightly obscure to read at first, but it has it's benefits.

I mean it would be even more confusing if someone else defined a function that had no relation to the class, so why not use the function?

For example:

$book = new Model('book');
// looks so close to the above, it's scary
$book = Model('book');

Other Pros or Cons?

解决方案

I do that occasionally. It sometimes can make code a bit more readable.

It's called factory procedures. But it makes most sense if they are less shallow. For example if depending on parameters such a method might return different objects (alternative placeholder/stub objects):

class User { ... }

function User($id) {
    return ($id < 0) ? new PlaceholderUser() : new User($id);
}   // or another *stub object* to support the application flow

But of course you can just use that for nicer looks. It's basically a cleaner approach than the commonplace static factory methods. But I would reserve such wrapper functions for objects which you really use a lot. It makes no sense to fill up the function scope with a wrapper call for each existing class.

And the common criticism here is: inexperienced developers can easily get confused by the object instantiation without new. (Not sure if that's true. But that's often said in this context.)

这篇关于Php函数名与类匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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