-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathattributes.xml
More file actions
391 lines (320 loc) · 11 KB
/
attributes.xml
File metadata and controls
391 lines (320 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<!-- EN-Revision: 0f14761ba340c6e49797706ac3f0cf1147d97253 Maintainer: Marqitos Status: ready -->
<!-- Reviewed: no -->
<chapter xml:id="language.attributes" xmlns="http://docbook.org/ns/docbook">
<title>Atributos</title>
<sect1 xml:id="language.attributes.overview">
<title>Descripción general de atributos</title>
<?phpdoc print-version-for="attributes"?>
<para>
Los atributos de PHP ofrecen metadatos estructurados y legibles por máquinas para clases, métodos,
funciones, parámetros, propiedades y constantes. Pueden ser inspeccionados en tiempo de ejecución
a través de la <link linkend="book.reflection">API de Reflection</link>, lo que permite un
comportamiento dinámico sin modificar el código. Los atributos proporcionan una forma declarativa de anotar
el código con metadatos.
</para>
<para>
Los atributos permiten desacoplar la implementación de una funcionalidad de su uso. Mientras que
las interfaces definen la estructura mediante la imposición de métodos, los atributos proporcionan metadatos en
varios elementos, incluidos métodos, funciones, propiedades y constantes. A diferencia de las interfaces,
que obligan a implementar métodos, los atributos anotan el código sin alterar su estructura.
</para>
<para>
Los atributos pueden complementar o reemplazar métodos opcionales de una interfaz al proporcionar metadatos en lugar de
una estructura impuesta. Considera una interfaz <literal>ActionHandler</literal> que representa una
operación en una aplicación. Algunas implementaciones pueden necesitar un paso de configuración, mientras que otras no.
En lugar de obligar a todas las clases que implementan <literal>ActionHandler</literal> a definir un
método <literal>setUp()</literal>, un atributo puede indicar los requisitos de configuración. Este enfoque
aumenta la flexibilidad, permitiendo que los atributos se apliquen varias veces cuando sea necesario.
</para>
<example>
<title>Implementación de métodos opcionales de una interfaz mediante atributos</title>
<programlisting role="php">
<![CDATA[
<?php
interface ActionHandler
{
public function execute();
}
#[Attribute]
class SetUp {}
class CopyFile implements ActionHandler
{
public string $fileName;
public string $targetDirectory;
#[SetUp]
public function fileExists()
{
if (!file_exists($this->fileName)) {
throw new RuntimeException("El archivo no existe");
}
}
#[SetUp]
public function targetDirectoryExists()
{
if (!file_exists($this->targetDirectory)) {
mkdir($this->targetDirectory);
} elseif (!is_dir($this->targetDirectory)) {
throw new RuntimeException("El directorio de destino $this->targetDirectory no es un directorio");
}
}
public function execute()
{
copy($this->fileName, $this->targetDirectory . '/' . basename($this->fileName));
}
}
function executeAction(ActionHandler $actionHandler)
{
$reflection = new ReflectionObject($actionHandler);
foreach ($reflection->getMethods() as $method) {
$attributes = $method->getAttributes(SetUp::class);
if (count($attributes) > 0) {
$methodName = $method->getName();
$actionHandler->$methodName();
}
}
$actionHandler->execute();
}
$copyAction = new CopyFile();
$copyAction->fileName = "/tmp/foo.jpg";
$copyAction->targetDirectory = "/home/user";
executeAction($copyAction);
]]>
</programlisting>
</example>
</sect1>
<sect1 xml:id="language.attributes.syntax">
<title>Sintaxis de atributos</title>
<para>
La sintaxis de atributos consta de varios componentes clave. Una declaración
de atributo comienza con <literal>#[</literal> y termina con
<literal>]</literal>. Dentro de esta, se pueden listar uno o más atributos,
separados por comas. El nombre del atributo puede ser no cualificado, cualificado
o totalmente cualificado, como se describe en <link linkend="language.namespaces.basics">Uso de los espacios de nombres: lo básico</link>.
Los argumentos para el atributo son opcionales y se encierran entre paréntesis
<literal>()</literal>. Los argumentos solo pueden ser valores literales o expresiones
constantes. Se admite la sintaxis de argumentos posicionales y nombrados.
</para>
<para>
Los nombres de los atributos y sus argumentos se resuelven en una clase, y los argumentos
se pasan a su constructor cuando se solicita una instancia del atributo
a través de la API de Reflection. Por lo tanto, se recomienda crear una clase
para cada atributo.
</para>
<example>
<title>Sintaxis de atributos</title>
<programlisting role="php">
<![CDATA[
<?php
// a.php
namespace MyExample;
use Attribute;
#[Attribute]
class MyAttribute
{
const VALUE = 'value';
private $value;
public function __construct($value = null)
{
$this->value = $value;
}
}
// b.php
namespace Another;
use MyExample\MyAttribute;
#[MyAttribute]
#[\MyExample\MyAttribute]
#[MyAttribute(1234)]
#[MyAttribute(value: 1234)]
#[MyAttribute(MyAttribute::VALUE)]
#[MyAttribute(array("key" => "value"))]
#[MyAttribute(100 + 200)]
class Thing
{
}
#[MyAttribute(1234), MyAttribute(5678)]
class AnotherThing
{
}
]]>
</programlisting>
</example>
</sect1>
<sect1 xml:id="language.attributes.reflection">
<title>Lectura de atributos con la API de Reflection</title>
<para>
Para acceder a los atributos de clases, métodos, funciones, parámetros, propiedades
y constantes de clase, utiliza el método <function>getAttributes</function> proporcionado
por la API de Reflection. Este método devuelve un array de instancias de <classname>ReflectionAttribute</classname>.
Estas instancias pueden consultarse para obtener el nombre del atributo, los argumentos, y
también pueden usarse para instanciar una instancia del atributo representado.
</para>
<para>
Separar la representación reflejada del atributo de su instancia real proporciona un mayor
control sobre la gestión de errores, como clases de atributos faltantes, argumentos mal escritos,
o valores ausentes. Los objetos de la clase de atributo se instancian solo después de llamar a
<function>ReflectionAttribute::newInstance</function>, lo que garantiza que la validación de los argumentos
se realice en ese momento.
</para>
<example>
<title>Lectura de atributos con la API de Reflection</title>
<programlisting role="php">
<![CDATA[
<?php
#[Attribute]
class MyAttribute
{
public $value;
public function __construct($value)
{
$this->value = $value;
}
}
#[MyAttribute(value: 1234)]
class Thing
{
}
function dumpAttributeData($reflection) {
$attributes = $reflection->getAttributes();
foreach ($attributes as $attribute) {
var_dump($attribute->getName());
var_dump($attribute->getArguments());
var_dump($attribute->newInstance());
}
}
dumpAttributeData(new ReflectionClass(Thing::class));
/*
string(11) "MyAttribute"
array(1) {
["value"]=>
int(1234)
}
object(MyAttribute)#3 (1) {
["value"]=>
int(1234)
}
*/
]]>
</programlisting>
</example>
<para>
En lugar de iterar sobre todos los atributos en la instancia de reflexión,
puedes recuperar solo aquellos de una clase de atributo específica pasando
el nombre de la clase de atributo como argumento.
</para>
<example>
<title>Lectura de atributos específicos utilizando la API de Reflection</title>
<programlisting role="php">
<![CDATA[
<?php
function dumpMyAttributeData($reflection) {
$attributes = $reflection->getAttributes(MyAttribute::class);
foreach ($attributes as $attribute) {
var_dump($attribute->getName());
var_dump($attribute->getArguments());
var_dump($attribute->newInstance());
}
}
dumpMyAttributeData(new ReflectionClass(Thing::class));
]]>
</programlisting>
</example>
</sect1>
<sect1 xml:id="language.attributes.classes">
<title>Declaración de clases de atributos</title>
<para>
Se recomienda definir una clase separada para cada atributo. En el caso más simple,
una clase vacía con la declaración <literal>#[Attribute]</literal> es suficiente.
El atributo puede ser importado desde el espacio de nombres global utilizando una declaración
<literal>use</literal>.
</para>
<example>
<title>Clase de atributo simple</title>
<programlisting role="php">
<![CDATA[
<?php
namespace Example;
use Attribute;
#[Attribute]
class MyAttribute
{
}
]]>
</programlisting>
</example>
<para>
Para restringir los tipos de declaraciones a los que se puede aplicar un atributo,
pasa una máscara de bits como primer argumento en la declaración
<literal>#[Attribute]</literal>
</para>
<example>
<title>Usar la especificación de destino para restringir dónde se pueden usar los atributos</title>
<programlisting role="php">
<![CDATA[
<?php
namespace Example;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION)]
class MyAttribute
{
}
]]>
</programlisting>
<para>
Declarar <classname>MyAttribute</classname> en otro tipo ahora generará una excepción durante
la llamada a <function>ReflectionAttribute::newInstance</function>
</para>
</example>
<para>Los siguientes destinos se pueden especificar:</para>
<simplelist>
<member><constant>Attribute::TARGET_CLASS</constant></member>
<member><constant>Attribute::TARGET_FUNCTION</constant></member>
<member><constant>Attribute::TARGET_METHOD</constant></member>
<member><constant>Attribute::TARGET_PROPERTY</constant></member>
<member><constant>Attribute::TARGET_CLASS_CONSTANT</constant></member>
<member><constant>Attribute::TARGET_PARAMETER</constant></member>
<member><constant>Attribute::TARGET_ALL</constant></member>
</simplelist>
<para>
Por defecto, un atributo solo se puede usar una vez por declaración. Para permitir
que un atributo sea repetible, especifícalo en la máscara de bits de la
declaración <literal>#[Attribute]</literal> utilizando el
flag <constant>Attribute::IS_REPEATABLE</constant>
</para>
<example>
<title>Usar IS_REPEATABLE para permitir que un atributo se use varias veces en una declaración</title>
<programlisting role="php">
<![CDATA[
<?php
namespace Example;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION | Attribute::IS_REPEATABLE)]
class MyAttribute
{
}
]]>
</programlisting>
</example>
</sect1>
</chapter>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->