Magento 2: tworzenie skryptów install i upgrade
Dzisiaj omówimy tworzenie skryptów install i upgrade w Magento 2.
W Magento za pomocą takich skryptów możemy dodawać/usuwać/modyfikować tabele w bazie danych. Na początek w naszym katalogu naszego modułu potrzebujemy stworzyć folder o nazwie Setup. Stworzymy nowy moduł Anna_Guestbook.
Tworzenie skryptu typu install
Skrypt Install jest wykonywany na samym początku, kiedy pierwszy raz instalujemy moduł. Jest to tak zwana pierwsza instalacja, gdzie dodawany jest nowy wpis do tabeli setup_module. Ten rodzaj skryptu uruchamiany jest tylko raz. Kolejne wersje instalacyjne będziemy tworzyć już w skrypcie typu upgrade.
W folderze Setup naszego modułu utwórz klasę o nazwie InstallSchema. Klasa ta musi implementować interfejs InstallSchemaInterface. Definicja tego interfejsu wygląda następująco:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\Setup; /** * Interface for DB schema installs of a module * * @api */ interface InstallSchemaInterface { /** * Installs DB schema for a module * * @param SchemaSetupInterface $setup * @param ModuleContextInterface $context * @return void */ public function install(SchemaSetupInterface $setup, ModuleContextInterface $context); } |
Nasza klasa InstallSchema, którą zaraz uzupełnimy:
|
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 |
<?php declare(strict_types=1); namespace Anna\Guestbook\Setup; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface { /** * Install DB schema for a module * * @param \Magento\Framework\Setup\SchemaSetupInterface $setup * @param \Magento\Framework\Setup\ModuleContextInterface $context * @throws \Zend_Db_Exception */ public function install(SchemaSetupInterface $setup, ModuleContextInterface $context): void { $installer = $setup; $installer->startSetup(); /** * Create guestbook table */ $questBookTable = $installer->getConnection() ->newTable($installer->getTable('guestbook')) ->addColumn( ... ) // @todo: setup $installer->getConnection()->createTable($questBookTable); $installer->endSetup(); } } |
Stwórzmy tabele questbook o następujących kolumnach:
- entry_id
- customer_id
- user_name
- subject
- content
- created_at
- update_at
Ostatecznie, nasz klasa InstallSchema wygląda następująco:
|
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 |
<?php declare(strict_types=1); namespace Anna\Guestbook\Setup; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; use Magento\Framework\DB\Ddl\Table as DbDdlTable; class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface { /** * Installs DB schema for a module * * @param \Magento\Framework\Setup\SchemaSetupInterface $setup * @param \Magento\Framework\Setup\ModuleContextInterface $context * @throws \Zend_Db_Exception */ public function install(SchemaSetupInterface $setup, ModuleContextInterface $context): void { $installer = $setup; $installer->startSetup(); /** * Create guestbook table */ $questBookTable = $installer->getConnection() ->newTable($installer->getTable('guestbook')) ->addColumn( 'entry_id', DbDdlTable::TYPE_INTEGER, null, ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true], 'Guestbook Entry Id') ->addColumn( 'customer_id', DbDdlTable::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => true], 'Customer Id' )->addColumn( 'user_name', DbDdlTable::TYPE_TEXT, 255, ['nullable' => true], 'Username' )->addColumn( 'subject', DbDdlTable::TYPE_TEXT, 255, ['nullable' => false], 'Entry subject' )->addColumn( 'content', DbDdlTable::TYPE_TEXT, null, ['nullable' => false], 'Entry message' )->addColumn( 'created_at', DbDdlTable::TYPE_TIMESTAMP, null, ['nullable' => false], 'Created At' )->addIndex( $installer->getIdxName('guestbook', 'customer_id'), ['customer_id'] )->addForeignKey( $installer->getFkName( $installer->getTable('guestbook'), 'customer_id', $installer->getTable('customer_entity'), 'entity_id'), 'customer_id', $installer->getTable('customer_entity'), 'entity_id', DbDdlTable::ACTION_CASCADE )->setComment('Customer Id'); $installer->getConnection()->createTable($questBookTable); $installer->endSetup(); } } |
W etc/module.xml określamy wersję modułu:
|
1 2 3 4 5 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Anna_Guestbook" setup_version="0.0.1" /> </config> |
Teraz potrzebujemy z konsoli wywołać komendę:
php bin/magento setup:upgrade
I sprawdzić czy udało się dodać pomyślnie naszą tabelkę. Jeśli wszystko było poprawnie, zobaczymy nowy wpis w tabeli setup_module.
Tworzenie skryptu typu upgrade
Utworzyliśmy tabelkę guestbook. Teraz chcielibyśmy dodać jeszcze jedną kolumnę, typu logicznego, o nazwie visible, aby określała ona widoczność wpisu (domyślnie niewidoczny). W tym celu potrzebujemy:
Podnieść wersję modułu, co robimy w pliku etc/module.xml:
|
1 2 3 4 5 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Anna_Guestbook" setup_version="0.0.2" /> </config> |
Stwórz klasę UpgradeSchema, która będzie implementować interfejs UpgradeSchemaInterface:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\Setup; /** * Interface for DB schema upgrades of a module * * @api */ interface UpgradeSchemaInterface { /** * Upgrades DB schema for a module * * @param SchemaSetupInterface $setup * @param ModuleContextInterface $context * @return void */ public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context); } |
W Magento 1 każdy skrypt upgrade stanowi jeden plik. W Magento 2 wszystko jest w jednym pliku, dlatego potrzebujemy sprawdzić wersję modułu. Nasza klasa UpgradeSchema (stworzona w katalogu Setup) wygląda następująco:
|
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 |
<?php declare(strict_types=1); namespace Anna\Guestbook\Setup; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; use Magento\Framework\Setup\UpgradeSchemaInterface; use Magento\Framework\DB\Ddl\Table as DbDdlTable; class UpgradeSchema implements UpgradeSchemaInterface { /** * Upgrades DB schema for a module * * @param \Magento\Framework\Setup\SchemaSetupInterface $setup * @param \Magento\Framework\Setup\ModuleContextInterface $context */ public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context): void { $installer = $setup; $connection = $installer->getConnection(); if (version_compare($context->getVersion(), '0.0.2', '<')) { // code to upgrade to 0.0.2 $connection->addColumn( $installer->getTable('guestbook'), 'visible', [ 'type' => DbDdlTable::TYPE_BOOLEAN, 'nullable' => false, 'default' => 0, 'length' => 1, 'comment' => 'Entry visibility', ] ); } $installer->endSetup(); } } |
Ostatnim krokiem będzie wywołanie komendy:
php bin/magento setup:upgrade
Podsumowanie
Magento 2, podobnie jak w Magento 1, w łatwy sposób pozwala nam tworzyć skrypty operujące na bazie danych.
W katalogu lib/Magento/Framework/Setup/README.md mamy informacje:
**Setup** provides interfaces that should be used or implemented by Setup data and schema installs, upgrades and uninstalls. ImplementInstallSchemaInterfaceand/orUpgradeSchemaInterfacefor DB schema install and/or upgrade. ImplementInstallDataInterfaceand/orUpgradeDataInterfacefor DB data install and/or upgrade. ImplementUninstallInterfacefor handling data removal during module uninstall. Setup application provides concrete implementation of a module context and setup DB/schema resources, so they can be used to determine current state of the module and get access to DB resource.
Ooo! Więc istnieje jeszcze coś takiego jak skrypty odpalane podczas odinstalowywania modułu! Aby odinstalować moduł, należy użyć komendy:
bin/magento module:uninstall Anna_Guestbook
Update: Od Magento 2.3 zamiast skryptów pisanych w pliku php, możemy wykorzystać coś takiego jak declerative schema i definicję tabeli tworzyć w pliku db_schema.xml! Jednak nie ma opcji, aby korzystać z dwóch rozwiązań jednocześnie.
Jak stworzyć przedstawioną tu tabelę za pomocą db_schema.xml znajdziesz tutaj.
Magento 2: Tworzenie grida w adminie za pomocą komponentu UI - Web Porgramming
15 października 2020 @ 20:45
[…] na temat tworzenia tabel za pomocą skrptów jak i […]
Magento 2: tworzenie tabeli za pomocą db_schema.xml - Web Porgramming
7 września 2022 @ 18:15
[…] W notce o install, upgrade skryptach został przedstawiony przykład z książką gości, gdzie została utworzona tabela guestbook. Tabela posiadała następujące kolumny: […]
Magento 2: tworzenie modeli CRUD - Web Programming
25 października 2023 @ 21:43
[…] Magento 2: tworzenie skryptów install i upgrade (wersja Magento < 2.3), […]