MageWork

Back to home

Add a new block

Open the packages/acme/etc/blocks.php file, and add a new block:

<?php

$config = [
    'acme' => [
        Core_Block::TYPE => [
            /* ... */
            'banner' => [ // The block identifier
                'class' => Acme_Block_Banner::class, // Optional
                'caption' => 'Welcome to MageWork!',
            ],
            /* ... */
        ],
    ],
];

Create a new class: packages/acme/app/Acme/Block/Banner.php

<?php

declare(strict_types=1);

class Acme_Block_Banner extends Core_Block
{
    public function execute(): void
    {
        $this->setImage('banner.png');
    }
}

The execute method is called before template rendering. It allows you to implement the code logic and inject data into the template.

Open any template file, example: packages/acme/template/page.phtml

<?= $this->getBlock('block/banner', ['alt' => 'My Banner'], 'banner') ?>

The first argument is the block template file in "packages/acme/template" (required).
The second argument is the data to send to the block (optional).
The last argument is the block identifier defined in the configuration file (optional).

Finally, create the template file: packages/acme/template/block/banner.phtml

<figure>
    <img src="<?= $this->getMedialUrl($this->getImage()) ?>" alt="<?= App::escapeHtmlAttr($this->getAlt()) ?>" />
    <figcaption><?= App::escapeHtml($this->getCaption()) ?></figcaption>
</figure>