MageWork

Back to home

Models

A model (Core_Model, type model) is the place for your business logic: database
access, computations, third-party calls, anything that is not display.

Create a model

Create a class in the Model directory of your package:

packages/Acme/Model/Customer.php

<?php

declare(strict_types=1);

class Acme_Model_Customer extends Core_Model
{
    public function getActive(): array
    {
        return App::db()
            ->where(['is_active =' => 1])
            ->getAll('customers');
    }
}

Core_Model extends DataObject, so a model also has getData() / setData() and the
magic getters and setters (see Data assignment).

Use a model

Instantiate the model with App::getSingleton() (shared instance) or App::getObject()
(new instance) — see Objects and class fallback.

<?php

/** @var Acme_Model_Customer $customer */
$customer = App::getSingleton('customer', Core_Model::TYPE);

$rows = $customer->getActive();

From another package, pass the package name as the third argument:

<?php

$customer = App::getSingleton('customer', Core_Model::TYPE, 'admin'); // Admin_Model_Customer

The execute() method

If a model (like any object built by the factory) defines an execute() method, it is
called automatically right after instantiation, before you use the object. See
Objects and class fallback.

<?php

declare(strict_types=1);

class Acme_Model_Cart extends Core_Model
{
    public function execute(): void
    {
        $this->setData('items', App::session()?->get('cart') ?: []);
    }
}