Creación de una nueva entidad en Magento 2
Actualización: 15/02/2018
En este post explicaré como crear desde cero una nueva entidad en Magento 2 con tres simples campos. Para ello, hablaré de todo lo relacionado con repositorios, API, interfaces y extensión de atributos y explicaremos dichos conceptos.
Cabe destacar que todo el módulo sigue las recomendaciones estándar de PHP.
A continuación pasaremos a explicar los pasos a seguir para conseguir nuestro objetivo.
Creación del módulo
app / code / Interactiv4 / Post / registration.php
1 2 3 4 5 6 7 8 9 10 | <?php /** * @author Interactiv4 Team * @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) * @package Interactiv4_Post */ use Magento\Framework\Component\ComponentRegistrar; ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Interactiv4_Post', __DIR__); |
app / code / Interactiv4 / Post / composer.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | { "name": "interactiv4/post", "description": "Example Module of Custom Entity", "require": { "php": "~7.0.0", "magento/magento-composer-installer": "*" }, "type": "magento2-module", "autoload": { "files": [ "registration.php" ], "psr-4": { "Interactiv4\\Post\\": "" } } } |
app / code / Interactiv4 / Post / etc / module.xml
1 2 3 4 5 6 7 8 9 10 | <?xml version="1.0"?> <!-- ~ @author Interactiv4 Team ~ @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) ~ @package Interactiv4_Post --> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Interactiv4_Post" setup_version="0.1.0"> </module> </config> |
Interfaz de modelo de datos
Esta interfaz, contendrá todos los getters y setters y definiremos en constantes el nombre de la tabla y campos de nuestra entidad en la base de datos.
app / code / Interactiv4 / Post / Api / Data / EntityInterface.php
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 | <?php /** * @author Interactiv4 Team * @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) * @package Interactiv4_Post */ namespace Interactiv4\Post\Api\Data; use Magento\Framework\Api\CustomAttributesDataInterface; /** * Interface EntityInterface */ interface EntityInterface extends CustomAttributesDataInterface { const TABLE = 'interactiv4_post_entity'; const ID = 'id'; const NAME = 'name'; const DESCRIPTION = 'description'; /** * Retrieve the name * * @return string */ public function getName(); /** * Set name * * @param string $name * @return $this */ public function setName($name); /** * Retrieve the description * * @return string */ public function getDescription(); /** * Set description * * @param string $description * @return $this */ public function setDescription($description); /** * Retrieve existing extension attributes object or create a new one. * * @return \Interactiv4\Post\Api\Data\EntityExtensionInterface|null */ public function getExtensionAttributes(); /** * Set an extension attributes object. * * @param \Interactiv4\Post\Api\Data\EntityExtensionInterface $extensionAttributes * @return $this */ public function setExtensionAttributes(\Interactiv4\Post\Api\Data\EntityExtensionInterface $extensionAttributes); } |
Extensión de atributos
Nuestra interfaz extiende de Magento \ Framework \ Api \ CustomAttributesDataInterface, la cual a su vez extiende de Magento \ Framework \ Api \ ExtensibleDataInterface.
La pregunta es, ¿para qué queremos que nuestra interfaz extienda de ExtensibleDataInterface? Esto sólo es necesario si deseamos que otros módulos puedan agregar atributos a nuestra entidad, ya que no podemos cambiar la interfaz cada vez que queramos añadir un nuevo atributo. Si es así, necesitamos agregar las funciones getExtensionAttributes() y setExtensionAttributes().
Es muy importante indicar de manera correcta la devolución y parámetro en estas 2 nuevas funciones. Magento generará esta interfaz si el nombre indicado es el correcto. Si la interfaz que queremos hacer extensible es Interactiv4 / Post / Api / Data / EntityInterface, entonces el tipo de extensión de atributos será Interactiv4 / Post / Api / Data / EntityExtensionInterface añadiendo la palabra Extension después del nombre de la entidad y antes del sufijo Interface.
Además de todo esto, cabe destacar que tanto la interfaz del modelo de datos como la del repositorio tienen que cumplir lo siguiente:
- Añadir todas las anotaciones PHPDoc para todos los parámetros y devoluciones de cada función.
- Usar el nombre completo de clases en el PHPDoc Block. Esto significa que la utilización del use al principio de las clases no funcionará.
Base de datos
El siguiente paso es crear el esquema de base de datos de nuestra nueva entidad.
app / code / Interactiv4 / Post / Setup / InstallSchema.php
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 | <?php /** * @author Interactiv4 Team * @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) * @package Interactiv4_Post */ namespace Interactiv4\Post\Setup; use Interactiv4\Post\Api\Data\EntityInterface; use Magento\Framework\DB\Ddl\Table; use Magento\Framework\Setup\InstallSchemaInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; /** * Class InstallSchema */ class InstallSchema implements InstallSchemaInterface { /** * {@inheritdoc} */ public function install(SchemaSetupInterface $setup, ModuleContextInterface $context) { $installer = $setup; $installer->startSetup(); $table = $installer->getConnection()->newTable( $installer->getTable(EntityInterface::TABLE) )->addColumn( EntityInterface::ID, Table::TYPE_INTEGER, null, ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true], 'Id' )->addColumn( EntityInterface::NAME, Table::TYPE_TEXT, 255, ['nullable' => true], 'Name' )->addColumn( EntityInterface::DESCRIPTION, Table::TYPE_TEXT, null, ['nullable' => true], 'Description' )->setComment( 'Custom Entity' ); $installer->getConnection()->createTable($table); $installer->endSetup(); } } |
Interfaz de repositorio
Los repositorios en Magento son los encargados de las funcionalidades CRUD. En Magento todos deben tener los métodos save, getById, delete y getList, en nuestro caso hemos añadido alguno más para hacerlo un poco más completo cubriendo tus necesidades.
app / code / Interactiv4 / Post / Api / EntityRepositoryInterface.php
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 | <?php /** * @author Interactiv4 Team * @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) * @package Interactiv4_Post */ namespace Interactiv4\Post\Api; /** * Interface EntityRepositoryInterface */ interface EntityRepositoryInterface { /** * Save entity * * @param \Interactiv4\Post\Api\Data\EntityInterface $entity * @return \Interactiv4\Post\Api\Data\EntityInterface */ public function save(\Interactiv4\Post\Api\Data\EntityInterface $entity); /** * Retrieve entity by id * * @param int $entityId * @return \Interactiv4\Post\Api\Data\EntityInterface * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function getById($entityId); /** * Retrieve entity by attribute * * @param $value * @param string|null $attributeCode * @return \Interactiv4\Post\Api\Data\EntityInterface * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function get($value, $attributeCode); /** * Delete $entity. * * @param \Interactiv4\Post\Api\Data\EntityInterface $entity * @return boolean * @throws \Magento\Framework\Exception\CouldNotDeleteException */ public function delete(\Interactiv4\Post\Api\Data\EntityInterface $entity); /** * Delete entity by ID. * * @param int $entityId * @return boolean * @throws \Magento\Framework\Exception\NoSuchEntityException * @throws \Magento\Framework\Exception\CouldNotDeleteException */ public function deleteById($entityId); /** * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria * @return \Interactiv4\Post\Api\Data\EntitySearchResultsInterface */ public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria); } |
SearchResults
El método getList del repositorio devuelve una instancia de SearchResultsInterface. Este método podría devolver un array de objetos que coincidan con el SearchCriteria especificado, pero crearemos esta interfaz para añadir información sobre los valores que debe devolver.
app / code / Interactiv4 / Post / Api / Data / EntitySearchResultsInterface.php
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 | <?php /** * @author Interactiv4 Team * @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) * @package Interactiv4_Post */ namespace Interactiv4\Post\Api\Data; /** * Interface EntitySearchResultsInterface */ interface EntitySearchResultsInterface extends \Magento\Framework\Api\SearchResultsInterface { /** * @return \Interactiv4\Post\Api\Data\EntityInterface[] */ public function getItems(); /** * @param \Interactiv4\Post\Api\Data\EntityInterface[] $items * @return void */ public function setItems(array $items); } |
Implementación del modelo de datos
Si nuestra interfaz de modelo de datos extiende de Magento \ Framework \ Api \ ExtensibleDataInterface, su implementación deberá extender de Magento \ Framework \ Model \ AbstractExtensibleModel.
app / code / Interactiv4 / Post / Model / Entity.php
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 | <?php /** * @author Interactiv4 Team * @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) * @package Interactiv4_Post */ namespace Interactiv4\Post\Model; use Interactiv4\Post\Api\Data\EntityExtensionInterface; use Interactiv4\Post\Api\Data\EntityInterface; use Interactiv4\Post\Model\ResourceModel\Entity as ResourceModelEntity; use Magento\Framework\DataObject\IdentityInterface; use Magento\Framework\Model\AbstractExtensibleModel; /** * Class Entity */ class Entity extends AbstractExtensibleModel implements EntityInterface, IdentityInterface { const CACHE_TAG = 'interactiv4_post_entity'; /** * @var string * @codingStandardsIgnoreStart */ protected $_cacheTag = 'interactiv4_post_entity'; // @codingStandardsIgnoreEnd /** * @var string * @codingStandardsIgnoreStart */ protected $_eventPrefix = 'interactiv4_post_entity'; // @codingStandardsIgnoreEnd /** * Initialize resource model * @codingStandardsIgnoreStart */ protected function _construct() { // @codingStandardsIgnoreEnd $this->_init(ResourceModelEntity::class); } /** * @inheritdoc */ public function getName() { return $this->_getData(self::NAME); } /** * @inheritdoc */ public function setName($name) { return $this->setData(self::NAME, $name); } /** * @inheritdoc */ public function getDescription() { return $this->_getData(self::DESCRIPTION); } /** * @inheritdoc */ public function setDescription($description) { return $this->setData(self::DESCRIPTION, $description); } /** * @inheritdoc */ public function getExtensionAttributes() { return $this->_getExtensionAttributes(); } /** * @inheritdoc */ public function setExtensionAttributes(EntityExtensionInterface $extensionAttributes) { return $this->_setExtensionAttributes($extensionAttributes); } public function getIdentities() { return [self::CACHE_TAG . '_' . $this->getId()]; } } |
En este ejemplo, nuestra clase implementa de Magento \ Framework \ DataObject \ IdentityInterface, esto hace que nuestro modelo use el método getIdentities(), el cual devuelve un único id para el modelo. IdentityInterface sólo se debe usar si nuestro modelo necesita refrescar la caché después de alguna operación en la base datos y mostrar la información en el frontend. El método getIdentities() es usado por Varnish para añadir la información en la cabecera como X-Magento-Tags.
- $_cacheTag: identificador único para usarlo dentro del almacenamiento de caché.
- $_eventPrefix: prefijo único usado a la hora de ejecutar los eventos. Esto hará que se creé un único evento para nuestra entidad, como por ejemplo interactiv4_post_entity_model_save_before.
Implementación de repositorio
app / code / Interactiv4 / Post / Model / EntityRepository.php
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 | <?php /** * @author Interactiv4 Team * @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) * @package Interactiv4_Post */ namespace Interactiv4\Post\Model; use Exception; use Interactiv4\Post\Api\Data\EntityInterface; use Interactiv4\Post\Api\Data\EntitySearchResultsInterface; use Interactiv4\Post\Api\Data\EntitySearchResultsInterfaceFactory; use Interactiv4\Post\Api\EntityRepositoryInterface; use Interactiv4\Post\Model\EntityFactory; use Interactiv4\Post\Model\ResourceModel\Entity as ResourceModelEntity; use Interactiv4\Post\Model\ResourceModel\Entity\Collection; use Interactiv4\Post\Model\ResourceModel\Entity\CollectionFactory; use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface; use Magento\Framework\Api\SearchCriteriaInterface; use Magento\Framework\Exception\CouldNotDeleteException; use Magento\Framework\Exception\NoSuchEntityException; /** * Class EntityRepository */ class EntityRepository implements EntityRepositoryInterface { /** * @var EntityFactory */ private $entityFactory; /** * @var ResourceModelEntity */ private $resourceModelEntity; /** * @var CollectionFactory */ private $entityCollectionFactory; /** * @var EntitySearchResultsInterfaceFactory */ private $entitySearchResultsInterfaceFactory; /** * @var CollectionProcessorInterface */ private $collectionProcessor; /** * @var JoinProcessorInterface */ private $extensionAttributesJoinProcessor; /** * EntityRepository constructor. * * @param EntityFactory $entityFactory * @param ResourceModelEntity $resourceModelEntity * @param CollectionFactory $entityCollectionFactory * @param EntitySearchResultsInterfaceFactory $entitySearchResultsInterfaceFactory * @param CollectionProcessorInterface $collectionProcessor * @param JoinProcessorInterface $extensionAttributesJoinProcessor */ public function __construct( EntityFactory $entityFactory, ResourceModelEntity $resourceModelEntity, CollectionFactory $entityCollectionFactory, EntitySearchResultsInterfaceFactory $entitySearchResultsInterfaceFactory, CollectionProcessorInterface $collectionProcessor, JoinProcessorInterface $extensionAttributesJoinProcessor ) { $this->entityFactory = $entityFactory; $this->resourceModelEntity = $resourceModelEntity; $this->entityCollectionFactory = $entityCollectionFactory; $this->entitySearchResultsInterfaceFactory = $entitySearchResultsInterfaceFactory; $this->collectionProcessor = $collectionProcessor; $this->extensionAttributesJoinProcessor = $extensionAttributesJoinProcessor; } /** * @inheritdoc */ public function save(EntityInterface $entity) { $this->resourceModelEntity->save($entity); return $entity; } /** * @inheritdoc */ public function getById($entityId) { return $this->get($entityId); } /** * @inheritdoc */ public function get($value, $attributeCode = null) { /** @var Entity $entity */ $entity = $this->entityFactory->create()->load($value, $attributeCode); if (!$entity->getId()) { throw new NoSuchEntityException(__('Unable to find entity')); } return $entity; } /** * @inheritdoc */ public function delete(EntityInterface $entity) { $entityId = $entity->getId(); try { $this->resourceModelEntity->delete($entity); } catch (Exception $e) { throw new CouldNotDeleteException( __('Unable to remove entity %1', $entityId) ); } return true; } /** * @inheritdoc */ public function deleteById($entityId) { $entity = $this->getById($entityId); return $this->delete($entity); } /** * @inheritdoc */ public function getList(SearchCriteriaInterface $searchCriteria) { /** @var Collection $collection */ $collection = $this->entityCollectionFactory->create(); $this->extensionAttributesJoinProcessor->process($collection, EntityInterface::class); $this->collectionProcessor->process($searchCriteria, $collection); /** @var EntitySearchResultsInterface $searchResults */ $searchResults = $this->entitySearchResultsInterfaceFactory->create(); $searchResults->setSearchCriteria($searchCriteria); $searchResults->setItems($collection->getItems()); $searchResults->setTotalCount($collection->getSize()); return $searchResults; } } |
Factory
En POO, un Factory es usado para instanciar un objeto. El nombre de la clase Factory es el nombre de la clase Model con el sufijo Factory. Esta clase Magento la genera automáticamente, por lo que no es necesario crearla. Para crear una instancia del objeto a partir de una clase Factory haremos lo siguiente:
$entity = $this->entityFactory->create();
Implementación SearchResults
Esta clase es la más simple de todas, ya que hereda toda su funcionalidad de Magento \ Framework \ Api \ SearchResults
app / code / Interactiv4 / Post / Model / EntitySearchResults.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php /** * @author Interactiv4 Team * @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) * @package Interactiv4_Post */ namespace Interactiv4\Post\Model; use Interactiv4\Post\Api\Data\EntitySearchResultsInterface; use Magento\Framework\Api\SearchResults; /** * Class EntitySearchResults */ class EntitySearchResults extends SearchResults implements EntitySearchResultsInterface { } |
ResourceModel
Como sabes, el modelo contiene la lógica de base de datos general, pero no ejecuta consultas SQL, de esto se encarga el resourceModel.
app / code / Interactiv4 / Post / Model / ResourceModel / Entity.php
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 | <?php /** * @author Interactiv4 Team * @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) * @package Interactiv4_Post */ namespace Interactiv4\Post\Model\ResourceModel; use Interactiv4\Post\Api\Data\EntityInterface; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; /** * Class Entity */ class Entity extends AbstractDb { /** * Initialize resource model * @codingStandardsIgnoreStart */ protected function _construct() { // @codingStandardsIgnoreEnd $this->_init(EntityInterface::TABLE, EntityInterface::ID); } } |
app / code / Interactiv4 / Post / Model / ResourceModel / Entity / Collection.php
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 | <?php /** * @author Interactiv4 Team * @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) * @package Interactiv4_Post */ namespace Interactiv4\Post\Model\ResourceModel\Entity; use Interactiv4\Post\Model\Entity as ModelEntity; use Interactiv4\Post\Model\ResourceModel\Entity as ResourceModelEntity; use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; /** * Class Collection */ class Collection extends AbstractCollection { /** * Initialize resource model collection * @codingStandardsIgnoreStart */ protected function _construct() { // @codingStandardsIgnoreEnd $this->_init(ModelEntity::class, ResourceModelEntity::class); } } |
Preference
Después de realizar todo lo comentado anteriormente, aún nos queda un último paso. Especificar las interfaces como dependencias de otras clases.
app / code / Interactiv4 / Post / etc / di.xml
1 2 3 4 5 6 7 8 9 10 11 | <?xml version="1.0"?> <!-- ~ @author Interactiv4 Team ~ @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) ~ @package Interactiv4_Post --> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Interactiv4\Post\Api\Data\EntityInterface" type="Interactiv4\Post\Model\Entity"/> <preference for="Interactiv4\Post\Api\Data\EntitySearchResultsInterface" type="Interactiv4\Post\Model\EntitySearchResults"/> <preference for="Interactiv4\Post\Api\EntityRepositoryInterface" type="Interactiv4\Post\Model\EntityRepository"/> </config> |
En todos los ejemplos escritos anteriormente, hacemos uso de las interfaces y no de sus clases, ya que una interfaz no debe cambiar en el futuro, pero una clase si puede hacerlo. De esta manera nos aseguramos que no haya problemas o conflictos en el futuro.
Habilitar API para el uso de terceros
app / code / Interactiv4 / Post / etc / webapi.xml
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 | <?xml version="1.0"?> <!-- ~ @author Interactiv4 Team ~ @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) ~ @package Interactiv4_Post --> <routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd"> <route method="POST" url="/V1/interactiv4_entities"> <service class="Interactiv4\Post\Api\EntityRepositoryInterface" method="save"/> <resources> <resource ref="self"/> </resources> </route> <route method="PUT" url="/V1/interactiv4_entities"> <service class="Interactiv4\Post\Api\EntityRepositoryInterface" method="save"/> <resources> <resource ref="self"/> </resources> </route> <route method="GET" url="/V1/interactiv4_entities/:entityId"> <service class="Interactiv4\Post\Api\EntityRepositoryInterface" method="getById"/> <resources> <resource ref="anonymous"/> </resources> </route> <route method="GET" url="/V1/interactiv4_entities/:value/:attributeCode/"> <service class="Interactiv4\Post\Api\EntityRepositoryInterface" method="get"/> <resources> <resource ref="anonymous"/> </resources> </route> <route method="DELETE" url="/V1/interactiv4_entities"> <service class="Interactiv4\Post\Api\EntityRepositoryInterface" method="delete"/> <resources> <resource ref="Interactiv4_Post::manage"/> </resources> </route> <route method="DELETE" url="/V1/interactiv4_entities:entityId"> <service class="Interactiv4\Post\Api\EntityRepositoryInterface" method="deleteById"/> <resources> <resource ref="Interactiv4_Post::manage"/> </resources> </route> <route method="GET" url="/V1/interactiv4_entities"> <service class="Interactiv4\Post\Api\EntityRepositoryInterface" method="getList"/> <resources> <resource ref="anonymouns"/> </resources> </route> </routes> |
Es importante que el nombre de los parámetros de la API coincidan con el nombre del parámetro del repositorio. El param entityId debe coincidir en /V1/interactiv4_entities/:entityId con public function getById($entityId);
Permisos
- <resource ref=”anonymous”/> hace que el recurso esté abierto públicamente sin ningún tipo de restricción.
- <resource ref=”self”/> hace que el recurso esté abierto sólo a clientes conectados.
- Para que un recurso sea solo accesible para usuarios administradores, este recurso debe de estar definido en /etc/acl.xml. En nuestro caso hemos definido el resource Interactiv4_Post::manage
app / code / Interactiv4 / Post / etc / acl.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?xml version="1.0"?> <!-- ~ @author Interactiv4 Team ~ @copyright Copyright (c) 2017 Interactiv4 (https://www.interactiv4.com) ~ @package Interactiv4_Post --> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd"> <acl> <resources> <resource id="Magento_Backend::admin"> <resource id="Interactiv4_Post::entity" title="Entities" translate="title" sortOrder="40"> <resource id="Interactiv4_Post::manage" title="All" translate="title" sortOrder="10" /> </resource> </resource> </resources> </acl> </config> |
Espero que os haya sido de ayuda y cualquier duda podéis dejar un comentario.
En este link podréis descargar el código completo.
Compartir
Suscríbete a nuestra newsletter
También te puede interesar
Usamos cookies de terceros para mejorar nuestros servicios y obtener datos estadísticos de tus hábitos de navegación. Si continúas navegando consideramos que aceptas su uso. Puedes obtener más información en Política de privacidad y cookies