Skip to content

Commit 46c938f

Browse files
committed
Add doc about traits
1 parent d4fb7c9 commit 46c938f

File tree

4 files changed

+121
-4
lines changed

4 files changed

+121
-4
lines changed

docs/create-model.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,8 @@ $orders = $user->getOrders();
273273

274274
For more information on defining relations, see [Define Relations](define-relations.md).
275275

276-
Also see [Using Dependency Injection With Active Record Model](using-di.md).
276+
Also see
277+
- [Using Dependency Injection With Active Record Model](using-di.md);
278+
- [Extending functionality with traits](traits/traits.md).
277279

278280
Back to [README](../README.md)

docs/traits/arrayable.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# ArrayableTrait
2+
3+
This trait provides methods to convert an `ActiveRecord` instance to an array format, using the `fields()`
4+
and `extraFields()` methods to determine which properties and relations should be included in the output.
5+
6+
## Methods
7+
8+
The following methods are provided by the `ArrayableTrait`:
9+
- `extraFields()` returns an associative array of relation names that can be included in the array representation
10+
of the record, with keys equal to values.
11+
- `fields()` returns an associative array of the record's property names, with keys equal to values.
12+
- `toArray()` converts the `ActiveRecord` instance to an array using the defined fields and extra fields.
13+
14+
## Usage
15+
16+
```php
17+
use Yiisoft\ActiveRecord\ActiveRecord;
18+
use Yiisoft\ActiveRecord\Trait\ArrayableTrait;
19+
20+
class User extends ActiveRecord
21+
{
22+
use ArrayableTrait;
23+
24+
// implement your own fields() and extraFields() if needed
25+
}
26+
27+
$user = new User();
28+
$data = $user->toArray(); // Converts the user instance to an array
29+
```
30+
31+
## Overrides
32+
33+
You can override the `fields()` and `extraFields()` methods in your `ActiveRecord` class to customize which fields
34+
and relations are included in the array representation.
35+
36+
Both `fields()` and `extraFields()` may return values that are either strings or `Closure` instances.

docs/traits/traits.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Traits
2+
3+
The library provides several traits that can be used to extend the functionality of `ActiveRecord` models.
4+
These traits can be included in your model classes to add specific behaviors or features.
5+
6+
- [ArrayableTrait](arrayable.md) provides `toArray()` method to convert a model to an array format;
7+
- `ArrayAccessTrait` allows accessing model properties and relations using array syntax;
8+
- `ArrayIteratorTrait` allows accessing model properties and relations iteratively;
9+
- `CustomConnectionTrait` allows using a custom database connection for a model;
10+
- `CustomTableNameTrait` allows using a custom table name for a model;
11+
- `FactoryTrait` allows creating models and relations using [yiisoft/factory](https://github.com/yiisoft/factory);
12+
- `MagicPropertiesTrait` stores properties in a private property and provides magic getters
13+
and setters for accessing the model properties and relations;
14+
- `MagicRelationsTrait` allows using methods with prefix `get` and suffix `Query` to define
15+
relations (e.g. `getOrdersQuery()` for `orders` relation);
16+
- `PrivateProopertiesTrait` allows using [private properties](../create-model.md#private-properties)
17+
in a model;
18+
- `RepositoryTrait` provides methods to interact with a model as a repository.
19+
20+
Back to [Create Active Record Model](../create-model.md)

src/Trait/ArrayableTrait.php

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Closure;
88
use Yiisoft\ActiveRecord\AbstractActiveRecord;
99
use Yiisoft\ActiveRecord\ActiveRecordInterface;
10+
use Yiisoft\Arrays\ArrayableInterface;
1011

1112
use function array_combine;
1213
use function array_keys;
@@ -19,14 +20,29 @@
1920
*
2021
* @method array relatedRecords()
2122
* @see AbstractActiveRecord::relatedRecords()
23+
*
24+
* @psalm-import-type FieldsArray from ArrayableInterface
2225
*/
2326
trait ArrayableTrait
2427
{
2528
use \Yiisoft\Arrays\ArrayableTrait;
2629

2730
/**
28-
* @return array The default implementation returns the names of the relations that have been populated into this
29-
* record.
31+
* Returns the list of fields that can be expanded further and returned by {@see toArray()}.
32+
*
33+
* This method is similar to {@see fields()} except that the list of fields returned by this method are not returned
34+
* by default by {@see toArray()}. Only when field names to be expanded are explicitly specified when calling
35+
* {@see toArray()}, will their values be exported.
36+
*
37+
* The default implementation returns the names of the relations defined in this `ActiveRecord` class indexed by
38+
* themselves.
39+
*
40+
* You may override this method to return a list of expandable fields.
41+
*
42+
* @return (string|Closure)[] The list of expandable field names or field definitions. Please refer
43+
* to {@see fields()} on the format of the return value.
44+
*
45+
* @psalm-return FieldsArray
3046
*/
3147
public function extraFields(): array
3248
{
@@ -36,7 +52,50 @@ public function extraFields(): array
3652
}
3753

3854
/**
39-
* @psalm-return array<string, string|Closure>
55+
* Returns the list of fields that should be returned by default by {@see toArray()}.
56+
*
57+
* A field is a named element in the returned array by {@see toArray()}.
58+
*
59+
* This method should return an array of field names or field definitions.
60+
* If the former, the field name will be treated as an object property name whose value will be used
61+
* as the field value. If the latter, the array key should be the field name while the array value should be
62+
* the corresponding field definition, which can be either an object property name or a PHP callable
63+
* returning the corresponding field value. The signature of the callable should be:
64+
*
65+
* ```php
66+
* function ($model, $field) {
67+
* // return field value
68+
* }
69+
* ```
70+
*
71+
* For example, the following code declares four fields:
72+
*
73+
* - `email`: the field name is the same as the property name `email`;
74+
* - `firstName` and `lastName`: the field names are `firstName` and `lastName`, and their
75+
* values are obtained from the `first_name` and `last_name` properties;
76+
* - `fullName`: the field name is `fullName`. Its value is obtained by concatenating `first_name`
77+
* and `last_name`.
78+
*
79+
* ```php
80+
* return [
81+
* 'email',
82+
* 'firstName' => 'first_name',
83+
* 'lastName' => 'last_name',
84+
* 'fullName' => function () {
85+
* return $this->first_name . ' ' . $this->last_name;
86+
* },
87+
* ];
88+
* ```
89+
*
90+
* In this method, you may also want to return different lists of fields based on some context
91+
* information. For example, depending on the privilege of the current application user,
92+
* you may return different sets of visible fields or filter out some fields.
93+
*
94+
* The default implementation returns the names of the properties of this record indexed by themselves.
95+
*
96+
* @return (string|Closure)[] The list of field names or field definitions.
97+
*
98+
* @psalm-return FieldsArray
4099
*/
41100
public function fields(): array
42101
{

0 commit comments

Comments
 (0)