Live data from Hacker News

Modern PHP Cheat Sheet

front-line-php.com

61–70 of 127 posts

Re: Modern PHP Cheat Sheet

#61
post #47

I've never understood why some programmers like to use ligatures, especially on a cheat sheet like this, which will be used primarily by people who aren't familiar with the syntax. It's not 'a' ⇒ 1, it's 'a' => 1, just write it out the correct way. Why are you trying to be fancy?

This is done by the used font, in the markup it's correct.

Looks like iosevka to me. Lovely font

EDIT: I wrongly assumed at a glance because of the shape of the $. On closer look the characters are much wider than iosevka. It's jetbrains mono

Re: Modern PHP Cheat Sheet

#62
post #40
post #36

Earlier quoted context omitted.

We do indeed create full blown classes for data objects. However, it is made easier with PHP 8.0 and 8.1 (released today). Typed properties, constructor properties, and Read-only properties can significantly reduce the code bloat. - https://php.watch/versions/8.0/constructor-property-promotio... - https://php.watch/versions/8.1/readonly

Can you directly cast an object / assoc array to an instance of such a class? If I have a function that receives eg a Message , it means an instance of the class right? So somehow my assoc.array/object still needs to be instanced, and if I do just $message = new Message($theData) … it doesn’t auto assign properties right? That would be handy though still very much boilerplate. I guessthe language is just designed for…

I never had to do this and I don't believe you can do this directly via a language construct but you can do it within a class via a method or trait or static function. This trait can then be applied to any class. Probably be better though to just have a create function that takes an input of type and coverts to class.

Anyway I was curious so I wanted to try this out with the trait method here is working code that illustrates this.

     $value)
            {
                if (!property_exists($class, $key)) continue;
                $class->$key = $value;
            }
            return $class;
        }
    }

    class Foo
    {
        use castFrom; // use the castFrom trait
        public string $str = 'blah';
        public int $num = 5;
        public function hello() { echo "{$this->str} : {$this->num}\n"; }
    }

    class Bar
    {
       use castFrom; // we can use the castFrom trait again and again
       public int $x = 0;
       public int $y = 0;
       public function hello() { echo ($this->x * $this->y) . "\n"; }
    }

    $data = ['str' => 'foo', 'num' => 7, 'x' => 3, 'y' => 7];

    $foo = Foo::castFrom($data);
    $foo->hello();

    print_r($foo);

    $obj = (object)$data;

    $bar = Bar::castFrom($obj);
    $bar->hello();

    print_r($bar);

    /* you could just use create functions form the class */
    class Creator
    {
        static public function createFromArray($data)  {} // create from array
        static public function createFromObject($data) {}   // create from object
        static public function createFromSerial($data) {}   // etc..
        static public function createFromJson($data)   {}
    }

EDIT: Added ugly check to make sure the type can be iterated over.

Re: Modern PHP Cheat Sheet

#63
post #52

Earlier quoted context omitted.

It's not clear to me what you're looking for. But you can cast arrays to objects. And you can use type declarations as arguments for functions.

Ok say I have a small class with an options object (I know perhaps not the best design...): class Foo { public function __construct(string $name, array $options) { $this->name = $name; if ($options->enableFlag) { ... I want to declare what $options are, in TS I could do: type TFooOptions = { enableFlag: boolean; userIds: number[]; } Then function __construct(string $name, TFooOptions $options) ... Otherwise how do I…

PHP doesn't do such structural typing, but Psalm[1] can do it statically. It calls them object-like arrays.[2]

[1]: https://psalm.dev/ [2]: https://psalm.dev/docs/annotating_code/type_syntax/array_typ...

Re: Modern PHP Cheat Sheet

#64
post #52

Earlier quoted context omitted.

It's not clear to me what you're looking for. But you can cast arrays to objects. And you can use type declarations as arguments for functions.

Ok say I have a small class with an options object (I know perhaps not the best design...): class Foo { public function __construct(string $name, array $options) { $this->name = $name; if ($options->enableFlag) { ... I want to declare what $options are, in TS I could do: type TFooOptions = { enableFlag: boolean; userIds: number[]; } Then function __construct(string $name, TFooOptions $options) ... Otherwise how do I…

You can force a type check that it's a specific type of object or interface rather than an array. But, no, you can't do what you're asking for directly.

Re: Modern PHP Cheat Sheet

#65
post #15
post #3

I like how PHP is evolving. I wouldn't say it's always a joy to use but it definitively improved a lot.

I really want to use PHP for one-off CGI scripts, (rsync files and done, deployed), but I really wish it had methods on primitive types. It hinders discoverability. It's annoying having to look up which function I need to use, and to find that there are many alternatives, most of which are deprecated. PHP stdlib needs an overhaul, IMO.

I agree, it'd be nice if the built in was more standardized and had more features.

However you do have options to choose from with php these days. Really well maintained libraries exist for basically everything you could want, often they are fast, well tested and modular. And it's nice because you can even choose the style you prefer with this.

Grab the symphony string lib for instance: https://symfony.com/doc/current/components/string.html

Re: Modern PHP Cheat Sheet

#66

I'm using Laravel/PHP for a new project and it's been a joy . A true joy. After spending the last 6+ years writing backend services in Node, PHP feels like a breath of fresh air. No restarting the server, no compiling errors from babel/typescript wackiness, no blocking threads, server-side templates out-of-the-box, and so much more. PHP has come a really long way, I really hope to see it's resurgence some day after e…

I'm writing PHP8 with the Symfony 5.3 framework at present too, and I'm also liking it. Provides what I need to build with and otherwise stays out the way.

The improvements over the lifespan of PHP7, and the new things in PHP8 make PHP such a nicer language to work with.

Re: Modern PHP Cheat Sheet

#67
post #41

As a JS dev it’s nice to see php imitate some newer js syntax like nullish coalescing, arrow function, … helps me to switch between the languages. It really needs a way to declare type of small data structures though, in a very concise way (no class boilerplate, for performance eg. going through 10000’s of entities). PS : on the other hand I’m starting to dislike how languages become "designed by committee", and lose…

[deleted]

Re: Modern PHP Cheat Sheet

#68
post #23

Earlier quoted context omitted.

Yeah, that's a terrible example since some places do use comma as a dollars/cents separator, and others don't. And some people use floats for currency (with the obvious caveats), and might read this as "_ is the same as a decimal point" . They really should just use a simpler example, like 10_000_000 being easier to read as "10 million" than 10000000.

> They really should just use a simpler example, like 10_000_000 being easier to read as "10 million" than 10000000. Declarations such as `$million = 1000 * 1000;` or `$seconds_in_day = 24 * 3600;` are very common, and in my opinion more readable than the ignored-underscore syntax.

Perhaps, though the underscore syntax works in Perl, Ruby, Java, etc.

And the context here is how to explain it, not whether it should exist and/or be used.

Re: Modern PHP Cheat Sheet

#69
post #34

Genuine question from a php hobbyist : what is the equivalent of Typescript’s ability to declare an object’s structure? It’s really weird to me, I mean don’t we do this all the time? Work with eg. an $options array/obj passedto a constructor, or say, a message decoded from JSON… I could write $name = $message[‘username’] … and there is no checks in ide or runtime, while the phpdoc will just document $message to be an…

The language type system doesn't quite support that yet in all scenarios. As of php 7/8 it's getting there but for what you are describing you'd need to use a static analysis tool still unfortunately.

Here's two of the most common ones. These are very mature and are very broadly used. Most editors also come with some support for these annotations so you often get help in the editor when something is wrong.

https://psalm.dev/docs/annotating_code/supported_annotations...

https://phpstan.org/writing-php-code/phpdoc-types

Re: Modern PHP Cheat Sheet

#70
post #47

I've never understood why some programmers like to use ligatures, especially on a cheat sheet like this, which will be used primarily by people who aren't familiar with the syntax. It's not 'a' ⇒ 1, it's 'a' => 1, just write it out the correct way. Why are you trying to be fancy?

Overall I think this is reasonable, but the font I'm using on my ide has ligatures and I think they provide a vastly better reading experience.
Post reply on HN