dongtan1009 2012-08-14 01:46
浏览 40

PHP PSR-1通过__call和__callStatic,这太难看了吗?

I have one specific class in my project that have a lot of static and class methods (this is on purpose, it makes more sense, in this case, to use one big class instead of many smaller ones).

The methods were defined using underscore case like method_name instead of PSR-1 compliant methodName and we are converting a bunch of stuff to PSR-1.

Now, we could use something like these methods (below) to allow the usage of either one (method_name and methodName). The advantage is that we do not risk to introduce new bugs and all the current code using it still works, and we can migrate them slowly.

<?php

// enable PSR-1 for class methods
public static function __callStatic($name, $args) {
    $toLower = function($c) { return '_'.strtolower($c[1]); };
    $underscoreCased = preg_replace_callback('/([A-Z])/', $toLower, $name);
    return forward_static_call_array(['ClassName', $underscoreCased], $args);
}

// enable PSR-1 for instance metods
public function __call($name, $args) {
    $toLower = function($c) { return '_'.strtolower($c[1]); };
    $underscoreCased = preg_replace_callback('/([A-Z])/', $toLower, $name);
    return call_user_func_array([$this, $underscoreCased], $args);
}

Now the question, is this too ugly? Should we avoid doing this despite the benefits listed above?

  • 写回答

1条回答 默认 最新

  • doulu5717 2013-01-15 22:53
    关注

    I wouldn't do it this way for several reasons:

    1. Magic functions (__call(), __callStatic(), __get(), ...) are slow, really, really slow, shown here
    2. Navigation: The class provides a method do_something but your code calls Object::doSomething(). This is an obstacle on my way to check the implementation, as I cannot simply Ctrl+F for doSomething. The same is true for IDEs and code completion.
    3. Why migrating at all? I guess you have more important things to do than slowly migrating method names in an internal, private project to a nomenclature defined for interoperability with other projects. Don't get me wrong, I wouldn't say, that the PSRs are nonsense, I just think that old code doesn't have to be forced into complying unless it's absolutely necessary. (Which in this case means, that this particular class is the only class left not complying to it in your whole project)

    So, basically my advice: If you really need to migrate this class to PSR-1, do it either all at once or let it be. But don't introduce magic functions only to comply to a naming scheme.

    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应