Skip to content

Commit

Permalink
Remove $db property from constructor (#368)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tigrov authored Jul 3, 2024
1 parent ccca25f commit cd71945
Show file tree
Hide file tree
Showing 63 changed files with 1,226 additions and 1,566 deletions.
50 changes: 40 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,26 +106,59 @@ final class User extends ActiveRecord

For more information, follow [Create Active Record Model](docs/create-model.md).

## Usage in controler with DI container autowiring
## Usage in controller with DI container autowiring

```php
use App\Entity\User;
use Psr\Http\Message\ResponseInterface;
use Yiisoft\ActiveRecord\ConnectionProvider;
use Yiisoft\Db\Connection\ConnectionInterface;

final class Register
{
public function register(
User $user
ConnectionInterface $db,
): ResponseInterface {
/** Connected AR by di autowired. */
ConnectionProvider::set($db);

$user = new User();
$user->setAttribute('username', 'yiiliveext');
$user->setAttribute('email', '[email protected]');
$user->save();
}
}
```

## Usage in controler with Active Record factory
## Usage with middleware

Add the middleware to the action, for example:

```php
use Yiisoft\ActiveRecord\ConnectionProviderMiddleware;
use Yiisoft\Router\Route;

Route::methods([Method::GET, Method::POST], '/user/register')
->middleware(ConnectionProviderMiddleware::class)
->action([Register::class, 'register'])
->name('user/register');
```

Or, if you use `yiisoft/config` and `yiisoft/middleware-dispatcher` packages, add the middleware to the configuration,
for example in `config/common/params.php` file:

```php
use Yiisoft\ActiveRecord\ConnectionProviderMiddleware;

return [
'middlewares' => [
ConnectionProviderMiddleware::class,
],
];
```

_For more information about how to configure middleware, follow [Middleware Documentation](https://github.com/yiisoft/docs/blob/master/guide/en/structure/middleware.md)_

Now you can use the Active Record in the action:

```php
use App\Entity\User;
Expand All @@ -134,12 +167,9 @@ use Yiisoft\ActiveRecord\ActiveRecordFactory;

final class Register
{
public function register(
ActiveRecordFactory $arFactory
): ResponseInterface {
/** Connected AR by factory di. */
$user = $arFactory->createAR(User::class);

public function register(): ResponseInterface
{
$user = new User();
$user->setAttribute('username', 'yiiliveext');
$user->setAttribute('email', '[email protected]');
$user->save();
Expand Down
8 changes: 8 additions & 0 deletions composer-require-checker.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"symbol-whitelist": [
"Psr\\Http\\Message\\ResponseInterface",
"Psr\\Http\\Message\\ServerRequestInterface",
"Psr\\Http\\Server\\MiddlewareInterface",
"Psr\\Http\\Server\\RequestHandlerInterface"
]
}
14 changes: 11 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@
"php": "^8.1",
"ext-json": "*",
"yiisoft/arrays": "^3.0",
"yiisoft/db": "dev-master",
"yiisoft/factory": "^1.0"
"yiisoft/db": "dev-master"
},
"require-dev": {
"maglnet/composer-require-checker": "^4.2",
Expand All @@ -46,7 +45,16 @@
"yiisoft/cache": "^3.0",
"yiisoft/db-sqlite": "dev-master",
"yiisoft/di": "^1.0",
"yiisoft/json": "^1.0"
"yiisoft/json": "^1.0",
"yiisoft/middleware-dispatcher": "^5.2"
},
"suggest": {
"yiisoft/db-sqlite": "For SQLite database support",
"yiisoft/db-mysql": "For MySQL database support",
"yiisoft/db-pgsql": "For PostgreSQL database support",
"yiisoft/db-mssql": "For MSSQL database support",
"yiisoft/db-oracle": "For Oracle database support",
"yiisoft/middleware-dispatcher": "For middleware support"
},
"autoload": {
"psr-4": {
Expand Down
23 changes: 9 additions & 14 deletions src/AbstractActiveRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,6 @@ abstract class AbstractActiveRecord implements ActiveRecordInterface
/** @psalm-var string[][] */
private array $relationsDependencies = [];

public function __construct(
private ConnectionInterface $db
) {
}

/**
* Returns the public and protected property values of an Active Record object.
*
Expand Down Expand Up @@ -89,7 +84,7 @@ public function delete(): int

public function deleteAll(array $condition = [], array $params = []): int
{
$command = $this->db->createCommand();
$command = $this->db()->createCommand();
$command->delete($this->getTableName(), $condition, $params);

return $command->execute();
Expand Down Expand Up @@ -328,7 +323,7 @@ public function insert(array $attributes = null): bool
*/
public function instantiateQuery(string|ActiveRecordInterface|Closure $arClass): ActiveQueryInterface
{
return new ActiveQuery($arClass, $this->db);
return new ActiveQuery($arClass);
}

/**
Expand Down Expand Up @@ -436,7 +431,7 @@ public function link(string $name, ActiveRecordInterface $arClass, array $extraC

$viaClass->insert();
} elseif (is_string($viaTable)) {
$this->db->createCommand()->insert($viaTable, $columns)->execute();
$this->db()->createCommand()->insert($viaTable, $columns)->execute();
}
} else {
$link = $relation->getLink();
Expand Down Expand Up @@ -718,7 +713,7 @@ public function update(array $attributeNames = null): int

public function updateAll(array $attributes, array|string $condition = [], array $params = []): int
{
$command = $this->db->createCommand();
$command = $this->db()->createCommand();

$command->update($this->getTableName(), $attributes, $condition, $params);

Expand Down Expand Up @@ -787,7 +782,7 @@ public function updateAllCounters(array $counters, array|string $condition = '',
$n++;
}

$command = $this->db->createCommand();
$command = $this->db()->createCommand();
$command->update($this->getTableName(), $counters, $condition, $params);

return $command->execute();
Expand Down Expand Up @@ -883,7 +878,7 @@ public function unlink(string $name, ActiveRecordInterface $arClass, bool $delet
$viaClass->updateAll($nulls, $columns);
}
} elseif (is_string($viaTable)) {
$command = $this->db->createCommand();
$command = $this->db()->createCommand();
if ($delete) {
$command->delete($viaTable, $columns)->execute();
} else {
Expand Down Expand Up @@ -996,7 +991,7 @@ public function unlinkAll(string $name, bool $delete = false): void
$viaClass->updateAll($nulls, $condition);
}
} elseif (is_string($viaTable)) {
$command = $this->db->createCommand();
$command = $this->db()->createCommand();
if ($delete) {
$command->delete($viaTable, $condition)->execute();
} else {
Expand Down Expand Up @@ -1252,8 +1247,8 @@ public function getTableName(): string
return '{{%' . DbStringHelper::pascalCaseToId(DbStringHelper::baseName(static::class)) . '}}';
}

protected function db(): ConnectionInterface
public function db(): ConnectionInterface
{
return $this->db;
return ConnectionProvider::get();
}
}
28 changes: 8 additions & 20 deletions src/ActiveQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use ReflectionException;
use Throwable;
use Yiisoft\Db\Command\CommandInterface;
use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Db\Exception\Exception;
use Yiisoft\Db\Exception\InvalidArgumentException;
use Yiisoft\Db\Exception\InvalidConfigException;
Expand All @@ -21,7 +20,6 @@
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
use Yiisoft\Definitions\Exception\CircularReferenceException;
use Yiisoft\Definitions\Exception\NotInstantiableException;
use Yiisoft\Factory\NotFoundException;

use function array_column;
use function array_combine;
Expand Down Expand Up @@ -118,10 +116,9 @@ class ActiveQuery extends Query implements ActiveQueryInterface
* @psalm-param ARClass $arClass
*/
final public function __construct(
protected string|ActiveRecordInterface|Closure $arClass,
protected ConnectionInterface $db
protected string|ActiveRecordInterface|Closure $arClass
) {
parent::__construct($db);
parent::__construct($this->getARInstance()->db());
}

/**
Expand Down Expand Up @@ -163,7 +160,6 @@ public function each(int $batchSize = 100): BatchQueryResultInterface
* @throws CircularReferenceException
* @throws Exception
* @throws InvalidConfigException
* @throws NotFoundException
* @throws NotInstantiableException
* @throws Throwable
* @throws \Yiisoft\Definitions\Exception\InvalidConfigException
Expand Down Expand Up @@ -287,7 +283,6 @@ public function populate(array $rows, Closure|string|null $indexBy = null): arra
* @throws CircularReferenceException
* @throws Exception
* @throws InvalidConfigException
* @throws NotFoundException
* @throws NotInstantiableException
*
* @return array The distinctive models.
Expand Down Expand Up @@ -473,7 +468,6 @@ public function resetJoinWith(): void
/**
* @throws CircularReferenceException
* @throws InvalidConfigException
* @throws NotFoundException
* @throws NotInstantiableException
* @throws \Yiisoft\Definitions\Exception\InvalidConfigException
*/
Expand Down Expand Up @@ -552,7 +546,6 @@ public function innerJoinWith(array|string $with, array|bool $eagerLoading = tru
*
* @throws CircularReferenceException
* @throws InvalidConfigException
* @throws NotFoundException
* @throws NotInstantiableException
* @throws \Yiisoft\Definitions\Exception\InvalidConfigException
*/
Expand Down Expand Up @@ -635,7 +628,6 @@ private function getJoinType(array|string $joinType, string $name): string
*
* @throws CircularReferenceException
* @throws InvalidConfigException
* @throws NotFoundException
* @throws NotInstantiableException
*/
private function getTableNameAndAlias(): array
Expand Down Expand Up @@ -672,9 +664,8 @@ private function getTableNameAndAlias(): array
* @param string $joinType The join type.
*
* @throws CircularReferenceException
* @throws NotFoundException
* @throws NotInstantiableException
* @throws \Yiisoft\Definitions\Exception\InvalidConfigException
* @throws InvalidConfigException
*/
private function joinWithRelation(ActiveQueryInterface $parent, ActiveQueryInterface $child, string $joinType): void
{
Expand Down Expand Up @@ -803,7 +794,7 @@ public function orOnCondition(array|string $condition, array $params = []): self
public function viaTable(string $tableName, array $link, callable $callable = null): self
{
$arClass = $this->primaryModel ?? $this->arClass;
$arClassInstance = new self($arClass, $this->db);
$arClassInstance = new self($arClass);

/** @psalm-suppress UndefinedMethod */
$relation = $arClassInstance->from([$tableName])->link($link)->multiple(true)->asArray();
Expand Down Expand Up @@ -839,7 +830,6 @@ public function alias(string $alias): self
/**
* @throws CircularReferenceException
* @throws InvalidArgumentException
* @throws NotFoundException
* @throws NotInstantiableException
* @throws \Yiisoft\Definitions\Exception\InvalidConfigException
*/
Expand All @@ -854,7 +844,6 @@ public function getTablesUsedInFrom(): array

/**
* @throws CircularReferenceException
* @throws NotFoundException
* @throws NotInstantiableException
* @throws \Yiisoft\Definitions\Exception\InvalidConfigException
*/
Expand Down Expand Up @@ -920,7 +909,6 @@ public function findAll(mixed $condition): array
* @throws CircularReferenceException
* @throws Exception
* @throws InvalidArgumentException
* @throws NotFoundException
* @throws NotInstantiableException
*/
protected function findByCondition(mixed $condition): static
Expand Down Expand Up @@ -982,7 +970,7 @@ public function getARClassName(): string
}

if ($this->arClass instanceof Closure) {
return ($this->arClass)($this->db)::class;
return ($this->arClass)()::class;
}

return $this->arClass;
Expand All @@ -995,18 +983,18 @@ public function getARInstance(): ActiveRecordInterface
}

if ($this->arClass instanceof Closure) {
return ($this->arClass)($this->db);
return ($this->arClass)();
}

/** @psalm-var class-string<ActiveRecordInterface> $class */
$class = $this->arClass;

return new $class($this->db);
return new $class();
}

private function createInstance(): static
{
return (new static($this->arClass, $this->db))
return (new static($this->arClass))
->where($this->getWhere())
->limit($this->getLimit())
->offset($this->getOffset())
Expand Down
7 changes: 1 addition & 6 deletions src/ActiveQueryInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,12 @@
use Closure;
use ReflectionException;
use Throwable;
use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Db\Exception\Exception;
use Yiisoft\Db\Exception\InvalidArgumentException;
use Yiisoft\Db\Exception\InvalidConfigException;
use Yiisoft\Db\Query\QueryInterface;
use Yiisoft\Definitions\Exception\CircularReferenceException;
use Yiisoft\Definitions\Exception\NotInstantiableException;
use Yiisoft\Factory\NotFoundException;

/**
* Defines the common interface to be implemented by active record query classes.
Expand All @@ -24,7 +22,7 @@
*
* A class implementing this interface should also use {@see ActiveQueryTrait} and {@see ActiveRelationTrait}.
*
* @psalm-type ARClass = class-string<ActiveRecordInterface>|ActiveRecordInterface|Closure(ConnectionInterface):ActiveRecordInterface
* @psalm-type ARClass = class-string<ActiveRecordInterface>|ActiveRecordInterface|Closure():ActiveRecordInterface
*/
interface ActiveQueryInterface extends QueryInterface
{
Expand Down Expand Up @@ -275,7 +273,6 @@ public function viaTable(string $tableName, array $link, callable $callable = nu
* @param string $alias The table alias.
*
* @throws CircularReferenceException
* @throws NotFoundException
* @throws NotInstantiableException
* @throws \Yiisoft\Definitions\Exception\InvalidConfigException
*/
Expand All @@ -288,7 +285,6 @@ public function alias(string $alias): self;
*
* @throws CircularReferenceException
* @throws InvalidArgumentException
* @throws NotFoundException
* @throws NotInstantiableException
* @throws \Yiisoft\Definitions\Exception\InvalidConfigException
*/
Expand Down Expand Up @@ -592,7 +588,6 @@ public function getLink(): array;
/**
* @throws CircularReferenceException
* @throws InvalidConfigException
* @throws NotFoundException
* @throws NotInstantiableException
* @return ActiveRecordInterface The model instance associated with this query.
*/
Expand Down
Loading

0 comments on commit cd71945

Please sign in to comment.