Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove $db property from constructor #368

Merged
merged 24 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
f32d7ac
Remove `$tableName` property from constructor
Tigrov Jun 25, 2024
207a53c
Apply fixes from StyleCI
StyleCIBot Jun 25, 2024
2e04d0f
Add comments to trait [skip ci]
Tigrov Jun 25, 2024
825a647
Add parameter type
Tigrov Jun 27, 2024
338d484
Remove `$db` property from constructor
Tigrov Jun 27, 2024
130337a
Update tests
Tigrov Jun 27, 2024
85764f7
Add `ConnectionProvider::isset()` method
Tigrov Jun 27, 2024
0c17288
Remove `$db` from `ActiveQuery` constructor
Tigrov Jun 27, 2024
d1f11d7
Remove `ActiveRecordFactory`
Tigrov Jun 28, 2024
ede81de
Add middleware and update README
Tigrov Jun 28, 2024
0216f59
Merge branch 'refs/heads/remove-tableName-property' into remove-db-pr…
Tigrov Jun 28, 2024
bad1290
Apply fixes from StyleCI
StyleCIBot Jun 28, 2024
20da8ba
Fix psalm issues
Tigrov Jun 28, 2024
74b7f72
Merge remote-tracking branch 'origin/remove-db-property' into remove-…
Tigrov Jun 28, 2024
de5a50a
Remove `yiisoft/factory` from composer
Tigrov Jun 28, 2024
94794c0
Fix psalm issues
Tigrov Jun 28, 2024
11494ee
Apply suggestions from code review [skip ci]
Tigrov Jul 1, 2024
270dab4
Merge branch 'refs/heads/master' into remove-db-property
Tigrov Jul 1, 2024
0bcbcc6
Update after merge
Tigrov Jul 1, 2024
cadcd07
Apply fixes from StyleCI
StyleCIBot Jul 1, 2024
1796d71
Add soc about config for middleware
Tigrov Jul 1, 2024
8c88e55
Add `ConnectionProvider` tests
Tigrov Jul 2, 2024
e5ff769
Add suggestions to composer.json
Tigrov Jul 2, 2024
6afc4eb
Configure `composer-require-checker`
Tigrov Jul 2, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 25 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,26 +106,44 @@ 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);
samdark marked this conversation as resolved.
Show resolved Hide resolved

$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');
```

Now you can use the Active Record in the action:

```php
use App\Entity\User;
Expand All @@ -134,12 +152,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
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@
"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",
"phpunit/phpunit": "^10.5",
"psr/http-server-middleware": "^1.0",
"rector/rector": "^1.0",
"roave/infection-static-analysis-plugin": "^1.34",
"spatie/phpunit-watcher": "^1.23",
Expand Down
30 changes: 10 additions & 20 deletions src/AbstractActiveRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,6 @@ abstract class AbstractActiveRecord implements ActiveRecordInterface
/** @psalm-var string[][] */
private array $relationsDependencies = [];

public function __construct(
private ConnectionInterface $db,
private string $tableName = ''
) {
}

/**
* Returns the public and protected property values of an Active Record object.
*
Expand Down Expand Up @@ -90,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 @@ -329,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 @@ -437,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 @@ -719,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 @@ -788,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 @@ -884,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 @@ -997,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 @@ -1250,15 +1244,11 @@ protected function resetDependentRelations(string $attribute): void

public function getTableName(): string
{
if ($this->tableName === '') {
$this->tableName = '{{%' . DbStringHelper::pascalCaseToId(DbStringHelper::baseName(static::class)) . '}}';
}

return $this->tableName;
return '{{%' . DbStringHelper::pascalCaseToId(DbStringHelper::baseName(static::class)) . '}}';
}

protected function db(): ConnectionInterface
public function db(): ConnectionInterface
{
return $this->db;
return ConnectionProvider::get();
}
}
29 changes: 8 additions & 21 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,11 +116,9 @@ class ActiveQuery extends Query implements ActiveQueryInterface
* @psalm-param ARClass $arClass
*/
final public function __construct(
protected string|ActiveRecordInterface|Closure $arClass,
protected ConnectionInterface $db,
private string $tableName = ''
protected string|ActiveRecordInterface|Closure $arClass
) {
parent::__construct($db);
parent::__construct($this->getARInstance()->db());
}

/**
Expand Down Expand Up @@ -164,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 @@ -288,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 @@ -474,7 +468,6 @@ public function resetJoinWith(): void
/**
* @throws CircularReferenceException
* @throws InvalidConfigException
* @throws NotFoundException
* @throws NotInstantiableException
* @throws \Yiisoft\Definitions\Exception\InvalidConfigException
*/
Expand Down Expand Up @@ -553,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 @@ -636,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 @@ -673,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 @@ -804,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 @@ -840,7 +830,6 @@ public function alias(string $alias): self
/**
* @throws CircularReferenceException
* @throws InvalidArgumentException
* @throws NotFoundException
* @throws NotInstantiableException
* @throws \Yiisoft\Definitions\Exception\InvalidConfigException
*/
Expand All @@ -855,7 +844,6 @@ public function getTablesUsedInFrom(): array

/**
* @throws CircularReferenceException
* @throws NotFoundException
* @throws NotInstantiableException
* @throws \Yiisoft\Definitions\Exception\InvalidConfigException
*/
Expand Down Expand Up @@ -921,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 @@ -983,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 @@ -996,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, $this->tableName);
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
Loading