Programmatically: How to create custom Magento models
Step 1: Create a new PHP class
In the app/code/local directory, create a new directory for your module (e.g., MyCompany_MyModule). Inside this directory, create a new PHP file (e.g., Model.php) that will contain your custom model class:
// app/code/local/MyCompany/MyModule/Model.php
namespace MyCompany\MyModule\Model;
class MyModel extends \Magento\Framework\Model\AbstractModel
{
// Your custom model code here
}
Step 2: Define the model's properties and methods
In the MyModel class, you can define properties and methods as needed. For example, let's say you want to create a model that represents an order item:
// app/code/local/MyCompany/MyModule/Model.php
namespace MyCompany\MyModule\Model;
class MyModel extends \Magento\Framework\Model\AbstractModel
{
protected $_orderItemTable;
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry\Registry $registry,
\MyCompany\MyModule\Model\ResourceModel\OrderItem $orderItemTable,
array $data = []
) {
parent::__construct($context, $registry, $data);
$this->_orderItemTable = $orderItemTable;
}
public function getOrderId()
{
// Return the order ID associated with this model
}
public function getItemName()
{
// Return the item name associated with this model
}
}
Step 3: Define the resource model
In Magento, the resource model is responsible for interacting with the database. You need to create a separate class that extends Magento\Framework\Model\ResourceModel\Db\AbstractDb. Let's create a resource model for our MyModel:
// app/code/local/MyCompany/MyModule/Model/ResourceModel.php
namespace MyCompany\MyModule\Model\ResourceModel;
class MyResource extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
protected function _construct()
{
$this->_init('my_table', 'entity_id');
}
public function load(\MyCompany\MyModule\Model\MyModel $model, $id)
{
// Load data from the database based on the given ID
}
public function save(\MyCompany\MyModule\Model\MyModel $model)
{
// Save data to the database
}
}
Step 4: Register the model and resource model
In your module's etc/module.xml file, register the model and resource model:
MyCompany\MyModule\Model
MyCompany\MyModule\Model\ResourceModel
Step 5: Use the custom model
Now you can use your custom model in your module or elsewhere in your Magento application:
// Example usage:
$model = \Magento\Framework\App\ObjectManager::getInstance()->get('MyCompany\MyModule\Model\MyModel');
$model->getOrderId(); // Get the order ID associated with this model
$model->getItemName(); // Get the item name associated with this model