Yii2: Adjust code style to be fully PSR-2 compatible

Created on 14 Jul 2016  路  9Comments  路  Source: yiisoft/yii2

Since we can break code, it's a good idea to adjust code style to be PSR-2 compatible (and probably prepare for the next code style as well).

Would allow us to:

  • Maintain less.
  • Use built-in IDE code styles.
under discussion enhancement

Most helpful comment

Primarily this is about _ for private properties.

All 9 comments

Primarily this is about _ for private properties.

We could use https://github.com/FriendsOfPHP/PHP-CS-Fixer to automate fixing CS.

PhpStorm + PSR1/2 code style + auto-format and done. That's what we do on all projects, less discussions on what and where spaces should be, etc.

Primarily this is about _ for private properties.

Using undescrore prefix (_) for the private properties is not some our whim - it is a practical necessity, which solves code ambiguity inside a class.
For example:

class Foo extends \yii\base\Object
{
    private $foo; // PSR compaible

    public function setFoo($value)  {...}

    public function getFoo()  {...}

    public function doSomething()
    {
        echo $this->foo; // accesses `foo` private variable directly - unable to use getter
    }
}

class Foo extends \yii\base\Object
{
    private $_foo; // not PSR compatible

    public function setFoo($value)  {...}

    public function getFoo()  {...}

    public function doSomething()
    {
        echo $this->_foo; // accesses `foo` private variable directly
        echo $this->foo; // accesses `foo` virtual property via getter
    }
}

Using same name for the internal fields and public properties may also cause a problem in some IDEs.
For example:

/**
 * @property string $foo
 */
class Foo extends \yii\base\Object
{
    private $foo;
   // ...
}

$foo = new Foo();
echo $foo->foo; // some IDE may complain here: "access to private field `foo`" dispite the doc comments

@samdark. I guess there is some consensus over here to have it PRS2. What are the next steps?

@dynasource yes but we can't do it because conflicts with properties via getters and setters @klimov-paul mentioned. I doubt we'll drop these in 2.1 so this is something for even further versions. I think the best thing to do here is to close it and write it down into 2.2 ideas.

hmmm...I wrongly assumed the underscore was actually part of this PSR. Alright. I withdraw my vote :)

Was this page helpful?
0 / 5 - 0 ratings