Magento 2 Factory Objects
In object oriented programming, a factory method is a method that’s used to instantiate an object. Factory methods exist to ensure system developers have control over how a particular object is instantiated, and how its arguments are passed in. There’s a certain school of though that thinks direct use of the new
keyword in programming
$object = new Foo;
is an anti-pattern, as directly instantiating an object creates a hard coded dependency in a method. Factory methods give the system owner the ability to control which objects are actually returned in a given context.
A factory object serves a similar purpose. In Magento 2, each CRUD model has a corresponding factory class. All factory class names are the name of the model class, appended with the word “Factory”. So, since our model class is named
Pulsestorm/ToDoCrud/Model/TodoItem
this means our factory class is named
Pulsestorm/ToDoCrud/Model/TodoItemFactory
To get an instance of the factory class, replace your block class with the following.
#File: app/code/Pulsestorm/ToDoCrud/Block/Main.php
<?php
namespace Pulsestorm\ToDoCrud\Block;
class Main extends \Magento\Framework\View\Element\Template
{
protected $toDoFactory;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Pulsestorm\ToDoCrud\Model\TodoItemFactory $toDoFactory
)
{
$this->toDoFactory = $toDoFactory;
parent::__construct($context);
}
function _prepareLayout()
{
var_dump(
get_class($this->toDoFactory)
);
exit;
}
}
What we’ve done here is use automatic constructor dependency injection to inject a Pulsestorm\ToDoCrud\Model\TodoItemFactory
factory object, and assign it to the toDoFactory
object property in the constructor method.
#File: app/code/Pulsestorm/ToDoCrud/Block/Main.php
protected $toDoFactory;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Pulsestorm\ToDoCrud\Model\TodoItemFactory $toDoFactory
)
{
$this->toDoFactory = $toDoFactory;
parent::__construct($context);
}
We also had to inject a block context object and pass that to our parent constructor. We’ll cover these context object in future articles, but if you’re curious about learning more, this quickies post is a good place to start.
In addition to injecting a factory into our block, we also added the following to our _prepareLayout
method
#File: app/code/Pulsestorm/ToDoCrud/Block/Main.php
function _prepareLayout()
{
var_dump(
get_class($this->toDoFactory)
);
exit;
}
This will dump the toDoFactory
‘s class name to the screen, and is a quick sanity check that our automatic constructor dependency injection worked. Reload your page with the above in place, and you should see the following
string 'Pulsestorm\ToDoCrud\Model\TodoItemFactory' (length=41)
Next, replace your _prepareLayout
method with this code
#File: app/code/Pulsestorm/ToDoCrud/Block/Main.php
function _prepareLayout()
{
$todo = $this->toDoFactory->create();
$todo->setData('item_text','Finish my Magento article')
->save();
var_dump('Done');
exit;
}
This code calls the create
method of our factory. This will instantiate a \Pulsestorm\ToDoCrud\Model\TodoItemFactory
object for us. Then, we set the item_text
property of our model, and call its save
method. Reload your page to run the above code, and then check your database table
mysql> select * from pulsestorm_todocrud_todoitem\G
*************************** 1. row ***************************
pulsestorm_todocrud_todoitem_id: 1
item_text: Finish my Magento article
date_completed: NULL
creation_time: NULL
update_time: NULL
is_active: 1
1 row in set (0.00 sec)
You’ll find that Magento has saved the information you requested. If you wanted to fetch this specific model again, you’d use code that looked like the following.
#File: app/code/Pulsestorm/ToDoCrud/Block/Main.php
function _prepareLayout()
{
$todo = $this->toDoFactory->create();
$todo = $todo->load(1);
var_dump($todo->getData());
exit;
}
Here we’ve used the factory to create our model, used the model’s load
method to load a model with the ID of 1
, and then dumped the model’s data using the various magic setter and getter methods available to a Magento 2 model.
#File: app/code/Pulsestorm/ToDoCrud/Block/Main.php
function _prepareLayout()
{
$todo = $this->toDoFactory->create();
$todo = $todo->load(1);
var_dump($todo->getData());
var_dump($todo->getItemText());
var_dump($todo->getData('item_text'));
exit;
}
Finally, if we wanted to use a CRUD model’s collection object, we’d use code that looked like this
#File: app/code/Pulsestorm/ToDoCrud/Block/Main.php
function _prepareLayout()
{
$todo = $this->toDoFactory->create();
$collection = $todo->getCollection();
foreach($collection as $item)
{
var_dump('Item ID: ' . $item->getId());
var_dump($item->getData());
}
exit;
}
Again, this code uses a factory object to create a CRUD model object. Then, we use the CRUD model object’s getCollection
method to fetch the model’s collection. Then, we iterate over the items returned by the collection.
Once instantiated via a factory, Magento 2’s CRUD models behave very similarly, if not identically, to their Magento 1 counterparts. If you’re curious about Magento 1’s CRUD objects, our venerable Magento 1 for PHP MVC Developers article may be of interest, as well as the Varien Data Collections article.
Where did the Factory Come From
You may be thinking to yourself — how did Magento instantiate a Pulsestorm/ToDoCrud/Model/TodoItemFactory
class if I never defined one? Factory classes are another instance of Magento 2 using code generation (first covered in our Proxy objectarticle). Whenever Magento’s object manager encounters a class name that ends in the word Factory
, it will automatically generate the class in the var/generation
folder if the class does not already exist. You can see your generated factory class at the following location
#File: var/generation/Pulsestorm/ToDoCrud/Model/TodoItemFactory.php
<?php
namespace Pulsestorm\ToDoCrud\Model;
/**
* Factory class for @see \Pulsestorm\ToDoCrud\Model\TodoItem
*/
class TodoItemFactory
{
//...
}
Magento 2 Factory Objects的更多相关文章
- Magento 2 instantiate object by Factory Objects
magento2的Factory Objects是用来实例化non-injectable classes,目前还不知道什么叫non-injectable classes. 可以用它来实例化Helper ...
- 时隔3年半Spring.NET 2.0终于正式Release了
一直很喜欢Spring.NET,不过2011年8月2日1.3.2正式release之后,再没有正式版本的release了. 直到4天前,Spring.NET 2.0 GA终于Release. http ...
- IBM MQ 与spring的整合
文件名:applicationContext-biz-mq.xml 新浪博客把里面的代码全部转换成HTML了,所以无法粘贴 可以查看CSDN里面的:http://blog.csdn.net/xiazo ...
- spring监听与IBM MQ JMS整合
spring xml 的配置: 文件名:applicationContext-biz-mq.xml <?xml version="1.0" encoding="UT ...
- Core J2EE Patterns - Service Locator--oracle官网
原文地址:http://www.oracle.com/technetwork/java/servicelocator-137181.html Context Service lookup and cr ...
- Object Pascal中文手册 经典教程
Object Pascal 参考手册 (Ver 0.1)ezdelphi@hotmail.com OverviewOverview(概述)Using object pascal(使用 object p ...
- Cannot locate factory for objects of type DefaultGradleConnector, as ConnectorServiceRegistry has been closed.
现象:更换android studio libs文件夹下的jar包,重新编译代码报错:Cannot locate factory for objects of type DefaultGradleCo ...
- Android Studio: Error:Cannot locate factory for objects of type DefaultGradleConnector, as ConnectorServiceRegistry
将别人的项目导入自己的环境下出现的问题. Gradle refresh failed; Error:Cannot locate factory for objects of type DefaultG ...
- 深入浅出设计模式——抽象工厂模式(Abstract Factory)
模式动机在工厂方法模式中具体工厂负责生产具体的产品,每一个具体工厂对应一种具体产品,工厂方法也具有唯一性,一般情况下,一个具体工厂中只有一个工厂方法或者一组重载的工厂方法.但是有时候我们需要一个工厂可 ...
随机推荐
- Flask框架(一):介绍与环境搭建
1.Flask介绍 Flask诞生于2010年,是Armin ronacher(人名)用 Python 语言基于 Werkzeug 工具箱编写的轻量级Web开发框架. Flask 本身相当于一个内核, ...
- 一文带你学习DWS数据库用户权限设计与管理
前言 本文将介绍DWS基于RBAC(Role-Based Access Control,基于角色的访问控制)的数据库用户权限管理.简单地说,一个用户拥有若干角色,每一个角色拥有若干权限.这样,就构造成 ...
- Python List insert()方法
描述 insert() 函数用于将指定对象插入列表的指定位置.高佣联盟 www.cgewang.com 语法 insert()方法语法: list.insert(index, obj) 参数 inde ...
- luogu P3285 [SCOI2014]方伯伯的OJ splay 线段树
LINK:方伯伯的OJ 一道稍有质量的线段树题目.不写LCT splay这辈子是不会单独写的 真的! 喜闻乐见的是 题目迷惑选手 \(op==1\) 查改用户在序列中的位置 题目压根没说位置啊 只有排 ...
- luogu 1587 [NOI2016]循环之美
LINK:NOI2016循环之美 这道题是 给出n m k 求出\(1\leq i\leq n,1\leq j\leq m\) \(\frac{i}{j}\)在k进制下是一个纯循环的. 由于数值相同的 ...
- java多线程的问题
1.多线程有什么用 (1) 发挥多核CPU的优势 单核CPU上所谓的"多线程"那是假的多线程,同一时间处理器只会处理一段逻辑,只不过线程之间切换得比较快,看着像多个线程" ...
- JS中的数组复制问题
JS中的数组复制问题 前言 首先提到复制,也就是拷贝问题,就必须要明确浅拷贝和深拷贝. 浅拷贝:B由A复制而来,改变B的内容,A也改变 深拷贝:B由A复制而来,改变B的内容,A的内容不会改变 总的来说 ...
- “随手记”开发记录day13
今天继续对我们的项目进行更改. 今天我们需要做的是增加“修改”功能.对于已经添加的记账记录,长按可以进行修改和删除的操作. 但是今天并没有完成……
- JS 弹出框拖拽
css代码 body { margin:; text-align: center; } .box { display: none; background-color: #fff !important; ...
- 制作的excel表格如何放到微信公众号文章中?
制作的excel表格如何放到微信公众号文章中? 我们都知道创建一个微信公众号,在公众号中发布一些文章是非常简单的,但公众号添加附件下载的功能却被限制,如今可以使用小程序“微附件”进行在公众号中添加附件 ...