and im working on the querying and i like to decalre what they are just incase
Assistant
Thanks for the additional info!
Given your code, you want to ensure the variables are properly typed after the null-coalescing assignment, so you have well-defined types before passing to the query methods.
Since directly casting with (?int) or (?string) does not exist, the best approach is:
First, you assign a value (possibly null) to $productId and $productSlug.
Then, in the next lines, you reassign the same variables after applying a normalization (casting) step.
The variable name remains the same, but the value changes.
Why is this allowed?
In PHP, variables are mutable — you can assign and reassign any variable as many times as you want.
So this:
php
$productId = $post['productId'] ?? null;
// At this point:
// $productId might be int, string, or null (depending on $post value)
$productId = $productId !== null ? (int) $productId : null;
// Now $productId is either an int (casted) or null
The same variable name is just overwritten with the new value. This is very normal and idiomatic.
Alternative ways:
You could assign to a new variable, but this is just extra naming, for example:
You want to create query methods in your ActiveQuery class (I'll assume something like ContentQuery or similar) to filter records by the defined status constants:
Here’s how you can add scoped query methods for these statuses:
php
/**
* Filter by Draft status
* @return static
*/
public function draft(): static
{
return $this->andWhere(['status' => self::STATUS_DRAFT]);
}
/**
* Filter by Published status
* @return static
*/
public function published(): static
{
return $this->andWhere(['status' => self::STATUS_PUBLISH]);
}
/**
* Filter by Sold Out status
* @return static
*/
public function soldOut(): static
{
return $this->andWhere(['status' => self::STATUS_SOLDOUT]);
}
This can improve clarity especially in longer or more complex code.
Summary:
PHP lets you read and assign the same variable in one line safely.
You "check" the old value, then assign the "new" value back into the same variable.
This is common and fine.
Using an extra variable can sometimes improve readability, especially if you want to keep raw and processed values separately.
If you want, I can show you an example with debug var_dump statements illustrating this step-by-step! Would you like that?
′
s
t
r
i
p
ei
d′
=>
for my userQuery to handle it:
code
<?php
declare(strict_types=1);
namespace app\models\query;
use yii\db\ActiveQuery;
use app\models\User;
use app\helpers\LogHelper;
/**
* Query
*
* This query class extends the base ActiveQuery to provide commonly used
* filtering methods (scopes) for the associated model. It improves
* code readability, reusability, and expressiveness by encapsulating
* query conditions into named methods.
*
* Typical usage involves method chaining to build complex queries in a clean,
* declarative style.
*
* Usage examples:
*
* Find all published records of a certain type:
*
* Model::find()->ofType('example')->published()->all();
*
* Find a single record by slug:
*
* Model::find()->slug('unique-slug')->one();
*
* Filter records by status or other attributes:
*
* Model::find()->draft()->all();
*
* Replace `Model` with the appropriate ActiveRecord class.
*/
class UserQuery extends ActiveQuery
{
/**
* {@inheritdoc}
* @param \yii\db\Connection|null $db the DB connection used for this query
* @return Content[] the list of models
*/
public function all($db = null): array
{
return parent::all($db);
}
/**
* {@inheritdoc}
* @param \yii\db\Connection|null $db the DB connection used for this query
* @return Content|array|null the model, or null if not found
*/
public function one($db = null)//: Leave blank, else error.
{
return parent::one($db);
}
/**
* Filter by Id
* @param int $id ID of the content
* @return static
* Usage:
*
* Model::find()->id(123)->one();
*/
public function id(int $id): static
{
return $this->andWhere(['id' => $id]);
}
/**
* User Stripe Customer Id
* @url https://stripe.com/docs/api/customers/object#customer_object-id
* @param int|string $stripeId
* @return static
*/
public function stripeId(int|string $stripeId): static
{
$id = (int) $stripeId;
return $this->andWhere(['stripe_id' => $id]);
}
/**
* Filter by Newest
* @ return static
*/
public function orderByNewest(): static
{
return $this->orderBy(['created_at' => SORT_DESC]);
}
/**
* Filter by Oldest
* @return static
*/
public function orderByOldest(): static
{
return $this->orderBy(['created_at' => SORT_ASC]);
}
/*
* Adds a condition to filter users that have a specific status bit set.
* @return static
*
* Usage example:
* To find users that are active (assuming STATUS_ACTIVE = 4):
*
* $activeUsers = User::find()->withStatus(User::STATUS_ACTIVE)->all();
*
* Or in chained queries:
*
* $user = User::find()
* ->where(['email' => $email])
* ->withStatus(User::STATUS_ACTIVE)
* ->one();
*
* Yii2 uses named parameters when preparing SQL queries.
* If multiple conditions reuse the same parameter name (e.g., ':flag') but with
* different bit flag values, PDO binds only one value to that name, causing the
* query to behave incorrectly.
* For example:
*
* (status & :flag) = :flag -- with :flag = 2
* AND
* (status & :flag) = 0 -- with :flag = 8
*
* Here, both conditions bind to the same ':flag', which PDO resolves to one value,
* resulting in something like `(status & 8) = 8 AND (status & 8) = 0` which
* is contradictory and will never match any rows.
*
* This method generates a unique parameter name for each call to avoid this conflict.
*
* @param int $statusFlag Bitwise flag to check.
* @return $this The query object itself.
*/
public function withStatus(int $statusFlag): static
{
$paramName = ':status_' . uniqid();
return $this->andWhere("(`status` & $paramName) = $paramName", [
$paramName => $statusFlag
]);
}
public function active(): static
{
return $this->withStatus(User::STATUS_ACTIVE)
->andWhere('status != :deleted', [':deleted' => User::STATUS_DELETED]);
}
public function inactive(): static
{
return $this->withStatus(User::STATUS_INACTIVE)
->andWhere('status != :deleted', [':deleted' => User::STATUS_DELETED]);
}
public function locked(): static
{
$query = $this->withStatus(User::STATUS_LOCKED)
->andWhere('status != :deleted', [':deleted' => User::STATUS_DELETED]);
LogHelper::debug("locked() called", [
'query' => $query,
'method' => __METHOD__
]);
return $query;
}
/**
* Filter users who are deleted.
* Since deleted status is exclusive, match it exactly.
* @return static
*/
public function deleted(): static
{
return $this->andWhere(['status' => User::STATUS_DELETED]);
}
/**
* Adds a condition to filter users that do NOT have a specific status bit set.
*
* Usage example:
* To find users that are NOT locked (assuming STATUS_LOCKED = 8):
*
* $unlockedUsers = User::find()->withoutStatus(User::STATUS_LOCKED)->all();
*
* Or combined with other conditions:
*
* $user = User::find()
* ->where(['email' => $email])
* ->withoutStatus(User::STATUS_LOCKED)
* ->one();
*
* This method also uses a unique parameter name to prevent collisions in the bound parameters,
* avoiding contradictory query conditions similar to `withStatus()`.
*
* @param int $statusFlag Bitwise flag to check absence of.
* @return $this The query object itself.
*/
public function withoutStatus(int $statusFlag): static
{
$paramName = ':status_' . uniqid();
return $this->andWhere("(`status` & $paramName) = 0", [
$paramName => $statusFlag
]);
}
public function notLocked(): static
{
$query = $this->withoutStatus(User::STATUS_LOCKED)
->andWhere('status != :deleted', [':deleted' => User::STATUS_DELETED]);
LogHelper::debug("notLocked() called", [
'query' => $query,
'method' => __METHOD__
]);
return $query;
}
public function notDeleted(): static
{
return $this->andWhere('status != :deleted', [':deleted' => User::STATUS_DELETED]);
}
/**
* Find all users with either active or inactive status.
*/
public function activeOrInactive(): static
{
$condition = '((`status` & :active) = :active) OR ((`status` & :inactive) = :inactive)';
return $this->andWhere($condition, [
':active' => User::STATUS_ACTIVE,
':inactive' => User::STATUS_INACTIVE,
])->andWhere('status != :deleted', [':deleted' => User::STATUS_DELETED]);
}
}
'cus_ABC123XYZ'
(int)
php
public function stripeId(string $stripeId): static
{
return $this->andWhere(['stripe_id' => $stripeId]);
}
(Or accept int|string and only cast if it’s integer.)
Optional: Full example for your UserQuery
php
public function email(string $email): static
{
return $this->andWhere(['email' => $email]);
}
public function stripeId(string $stripeId): static
{
return $this->andWhere(['stripe_id' => $stripeId]);
}
public function active(): static
{
return $this->withStatus(User::STATUS_ACTIVE)
->andWhere('status != :deleted', [':deleted' => User::STATUS_DELETED]);
}