美文网首页PHP经验分享PHP实战
【轻知识】php的一点最佳实践

【轻知识】php的一点最佳实践

作者: 言十年 | 来源:发表于2019-05-16 13:37 被阅读3次

coding style方面

php 整洁之道https://github.com/jupeter/clean-code-php

php最佳实践http://laravel-china.github.io/php-the-right-way/

《25 Easy PHP7 Micro-Optimizations》https://blobfolio.com/2017/09/25-easy-php7-micro-optimizations/

使用php 7 语法 http://www.php7.site/book/php7/new-features-7.html

强烈建议用7 style

image.png

虽然看起来没什么,但是细想,思维习惯(比如精简、清楚返回值是什么类型、减少类型判断的代码)会改变一些。另外当你用强类型语言,你发现这些习惯也会帮到你。

代码格式化

PHP Coding Standards Fixer(PHP-CS-Fixer)

配置 git hooks https://github.com/amphp/php-cs-fixer-config

可以加到编译器中,用快捷键格式化代码。https://blog.csdn.net/m0_38092942/article/details/80006144

代码提示问题

当你发现yaf代码不好追。或者你的liblab不好追。或者laravel什么的。

你可以把代码或者帮助文件(可以提示的帮助性php文件,比如laravel有larave-ide-helper,其他的自行找,加入到你的ide工具中。)

温馨提示:为了查看框架代码。yaf的帮助文档https://github.com/elad-yosifon/php-yaf-doc

以phpstorm为例 ,加入到如下地方,就能代码提示了。

image.png

做法如下(或者从setting入口进入也可以)

image.png

那么你在纠结call 跟call static 的代码无法提示?

对于我们call方法,call_static 方法调用的。

可以通过写@method的方式,进行代码提示。也告诉别人哪些方法可以用。比如,yaf框架,yaf本身就有getPost()。调用示例是$this->getPost("name","")。但是我们在baseaction里面又自己实现了_post方法。作用跟框架的方法一样。

比如你想用框架自带的一些方法。在baseaction加上如下代码。

    public function __call($name, $arguments)
    {
        if (!method_exists($this, $name)) {
            if (method_exists($this->getRequest(), $name)) {
                return call_user_func_array([$this->getRequest(), $name], $arguments);
            } else if (method_exists($this->getresponse(), $name)) {
                return call_user_func_array([$this->getresponse(), $name], $arguments);
            }
        }
        throw new \Exception('Unsupported method:' . $name);
    }

然后在文件的头部这些写@method

image.png

使用参考 https://docs.phpdoc.org/references/phpdoc/tags/method.html

相关文章

网友评论

    本文标题:【轻知识】php的一点最佳实践

    本文链接:https://www.haomeiwen.com/subject/jjtiaqtx.html