Why clone an object in yii2 pagination
Here in the pagination doc they use $ countQuery = clone $ query; What for? It works without cloning and produces the same sql queries as a result as the clone. Help me find the difference.
source to share
The advantage of clone over creating a new object is that all properties will be copied to the new object instead of resetting them. This is very useful when using the query builder. In the example with the official doc we have:
$query = Article::find()->where(['status' => 1]);
$countQuery = clone $query;
If you get a dump from $query
and $countQuery
, you can see $countQuery
- this is a new object, similar to $query
as well status=>1
. In these cases, we use a clone to have two nearly identical queries with slight differences. Thus, you can have multiple behaviors from Query Object
. This will be more useful if you have complex query builder objects that might be slightly different from your existing query. For example, you need to have union
. You don't want to overwrite your object Query
, do you? So the best way is to get a clone from an existing request and then change its behavior.
source to share