in php object oriented programming oop cqrs refactor cleanc code ~ read.

Command/Query Segregation in PHP

This is gonna be a short post regarding the command query segregation in object oriented programming.

What is Command/Query Segregation?

It means that a method is either a command performing an action, or a query that returns data, but not both. Being purely action-performing methods, commands always have a void return type or not return anything in PHP. Queries, on the other hand, should be idempotent, that is, they don't have any visible side effects on the system.

Show me some examples of commands and queries?

<?php 

class CQS  
{
    private name;
    private age;

    public function __construct($name, $age) 
    {
        $this->name = $name; 
        $this->age = $age; 
    }

    public command()
    {
        $this->name = 'Well';
    }

    public query()
    {
        return ($this->age > 18) ? true : false;
    }
}

As you can see the above code that the command method return nothing and just modify the $name property while query method will return either true or false based on the number of $age.

End

Knowing the difference between what is command and what is query could help us better writing softwares. For example if you are doing a lot of unit testing, it will be better to use query and assert on it while it is a little bit hard to test command. As always if you have any opinions or ideas please leave it below. Thanks.

comments powered by Disqus