Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
AbstractModel.php
Go to the documentation of this file.
1 <?php
7 
9 
20 {
26  protected $_eventPrefix = 'core_abstract';
27 
35  protected $_eventObject = 'object';
36 
42  protected $_idFieldName = 'id';
43 
48  protected $_hasDataChanges = false;
49 
55  protected $_origData;
56 
62  protected $_isDeleted = false;
63 
69  protected $_resource;
70 
77 
83  protected $_resourceName;
84 
90  protected $_collectionName;
91 
99  protected $_cacheTag = false;
100 
108  protected $_dataSaveAllowed = true;
109 
115  protected $_isObjectNew = null;
116 
122  protected $_validatorBeforeSave = null;
123 
129  protected $_eventManager;
130 
136  protected $_cacheManager;
137 
141  protected $_registry;
142 
146  protected $_logger;
147 
151  protected $_appState;
152 
156  protected $_actionValidator;
157 
163  protected $storedData = [];
164 
172  public function __construct(
173  \Magento\Framework\Model\Context $context,
174  \Magento\Framework\Registry $registry,
175  \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
176  \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
177  array $data = []
178  ) {
179  $this->_registry = $registry;
180  $this->_appState = $context->getAppState();
181  $this->_eventManager = $context->getEventDispatcher();
182  $this->_cacheManager = $context->getCacheManager();
183  $this->_resource = $resource;
184  $this->_resourceCollection = $resourceCollection;
185  $this->_logger = $context->getLogger();
186  $this->_actionValidator = $context->getActionValidator();
187 
188  if (method_exists($this->_resource, 'getIdFieldName')
189  || $this->_resource instanceof \Magento\Framework\DataObject
190  ) {
191  $this->_idFieldName = $this->_getResource()->getIdFieldName();
192  }
193 
194  parent::__construct($data);
195  $this->_construct();
196  }
197 
203  protected function _construct()
204  {
205  }
206 
213  protected function _init($resourceModel)
214  {
216  $this->_idFieldName = $this->_getResource()->getIdFieldName();
217  }
218 
222  public function __sleep()
223  {
224  $properties = array_keys(get_object_vars($this));
225  $properties = array_diff(
226  $properties,
227  [
228  '_eventManager',
229  '_cacheManager',
230  '_registry',
231  '_appState',
232  '_actionValidator',
233  '_logger',
234  '_resourceCollection',
235  '_resource',
236  ]
237  );
238  return $properties;
239  }
240 
246  public function __wakeup()
247  {
249  $this->_registry = $objectManager->get(\Magento\Framework\Registry::class);
250 
251  $context = $objectManager->get(\Magento\Framework\Model\Context::class);
252  if ($context instanceof \Magento\Framework\Model\Context) {
253  $this->_appState = $context->getAppState();
254  $this->_eventManager = $context->getEventDispatcher();
255  $this->_cacheManager = $context->getCacheManager();
256  $this->_logger = $context->getLogger();
257  $this->_actionValidator = $context->getActionValidator();
258  }
259  }
260 
267  public function setIdFieldName($name)
268  {
269  $this->_idFieldName = $name;
270  return $this;
271  }
272 
278  public function getIdFieldName()
279  {
280  return $this->_idFieldName;
281  }
282 
288  public function getId()
289  {
290  return $this->_getData($this->_idFieldName);
291  }
292 
299  public function setId($value)
300  {
301  $this->setData($this->_idFieldName, $value);
302  return $this;
303  }
304 
311  public function isDeleted($isDeleted = null)
312  {
314  if ($isDeleted !== null) {
315  $this->_isDeleted = $isDeleted;
316  }
317  return $result;
318  }
319 
328  public function hasDataChanges()
329  {
330  return $this->_hasDataChanges;
331  }
332 
345  public function setData($key, $value = null)
346  {
347  if ($key === (array)$key) {
348  if ($this->_data !== $key) {
349  $this->_hasDataChanges = true;
350  }
351  $this->_data = $key;
352  } else {
353  if (!array_key_exists($key, $this->_data) || $this->_data[$key] !== $value) {
354  $this->_hasDataChanges = true;
355  }
356  $this->_data[$key] = $value;
357  }
358  return $this;
359  }
360 
367  public function unsetData($key = null)
368  {
369  if ($key === null) {
370  $this->setData([]);
371  } elseif (is_string($key)) {
372  if (isset($this->_data[$key]) || array_key_exists($key, $this->_data)) {
373  $this->_hasDataChanges = true;
374  unset($this->_data[$key]);
375  }
376  } elseif ($key === (array)$key) {
377  foreach ($key as $element) {
378  $this->unsetData($element);
379  }
380  }
381  return $this;
382  }
383 
390  public function setDataChanges($value)
391  {
392  $this->_hasDataChanges = (bool)$value;
393  return $this;
394  }
395 
402  public function getOrigData($key = null)
403  {
404  if ($key === null) {
405  return $this->_origData;
406  }
407  if (isset($this->_origData[$key])) {
408  return $this->_origData[$key];
409  }
410  return null;
411  }
412 
422  public function setOrigData($key = null, $data = null)
423  {
424  if ($key === null) {
425  $this->_origData = $this->_data;
426  } else {
427  $this->_origData[$key] = $data;
428  }
429  return $this;
430  }
431 
438  public function dataHasChangedFor($field)
439  {
440  $newData = $this->getData($field);
441  $origData = $this->getOrigData($field);
442  return $newData != $origData;
443  }
444 
454  protected function _setResourceModel($resourceName, $collectionName = null)
455  {
456  $this->_resourceName = $resourceName;
457  if ($collectionName === null) {
458  $collectionName = $resourceName . '\\' . 'Collection';
459  }
460  $this->_collectionName = $collectionName;
461  }
462 
470  protected function _getResource()
471  {
472  if (empty($this->_resourceName) && empty($this->_resource)) {
473  throw new \Magento\Framework\Exception\LocalizedException(
474  new \Magento\Framework\Phrase('The resource isn\'t set.')
475  );
476  }
477 
478  return $this->_resource ?: \Magento\Framework\App\ObjectManager::getInstance()->get($this->_resourceName);
479  }
480 
486  public function getResourceName()
487  {
488  return $this->_resource ? get_class($this->_resource) : ($this->_resourceName ? $this->_resourceName : null);
489  }
490 
499  public function getResourceCollection()
500  {
501  if (empty($this->_resourceCollection) && empty($this->_collectionName)) {
502  throw new \Magento\Framework\Exception\LocalizedException(
503  new \Magento\Framework\Phrase('Model collection resource name is not defined.')
504  );
505  }
506  return $this->_resourceCollection ? clone $this
507  ->_resourceCollection : \Magento\Framework\App\ObjectManager::getInstance()
508  ->create(
509  $this->_collectionName
510  );
511  }
512 
520  public function getCollection()
521  {
522  return $this->getResourceCollection();
523  }
524 
535  public function load($modelId, $field = null)
536  {
537  $this->_getResource()->load($this, $modelId, $field);
538  return $this;
539  }
540 
546  protected function _getEventData()
547  {
548  return [
549  'data_object' => $this,
550  $this->_eventObject => $this,
551  ];
552  }
553 
561  protected function _beforeLoad($modelId, $field = null)
562  {
563  $params = ['object' => $this, 'field' => $field, 'value' => $modelId];
564  $this->_eventManager->dispatch('model_load_before', $params);
565  $params = array_merge($params, $this->_getEventData());
566  $this->_eventManager->dispatch($this->_eventPrefix . '_load_before', $params);
567  return $this;
568  }
569 
575  protected function _afterLoad()
576  {
577  $this->_eventManager->dispatch('model_load_after', ['object' => $this]);
578  $this->_eventManager->dispatch($this->_eventPrefix . '_load_after', $this->_getEventData());
579  return $this;
580  }
581 
590  public function beforeLoad($identifier, $field = null)
591  {
592  $this->_beforeLoad($identifier, $field);
593  }
594 
600  public function afterLoad()
601  {
602  $this->_afterLoad();
603  $this->updateStoredData();
604  return $this;
605  }
606 
614  protected function _hasModelChanged()
615  {
616  return $this->hasDataChanges();
617  }
618 
622  public function isSaveAllowed()
623  {
624  return (bool) $this->_dataSaveAllowed;
625  }
626 
631  public function setHasDataChanges($flag)
632  {
633  $this->_hasDataChanges = $flag;
634  }
635 
646  public function save()
647  {
648  $this->_getResource()->save($this);
649  return $this;
650  }
651 
657  public function afterCommitCallback()
658  {
659  $this->_eventManager->dispatch('model_save_commit_after', ['object' => $this]);
660  $this->_eventManager->dispatch($this->_eventPrefix . '_save_commit_after', $this->_getEventData());
661  return $this;
662  }
663 
673  public function isObjectNew($flag = null)
674  {
675  if ($flag !== null) {
676  $this->_isObjectNew = $flag;
677  }
678  if ($this->_isObjectNew !== null) {
679  return $this->_isObjectNew;
680  }
681  return !(bool)$this->getId();
682  }
683 
689  public function beforeSave()
690  {
691  if (!$this->getId()) {
692  $this->isObjectNew(true);
693  }
694  $this->_eventManager->dispatch('model_save_before', ['object' => $this]);
695  $this->_eventManager->dispatch($this->_eventPrefix . '_save_before', $this->_getEventData());
696  return $this;
697  }
698 
705  public function validateBeforeSave()
706  {
707  $validator = $this->_getValidatorBeforeSave();
708  if ($validator && !$validator->isValid($this)) {
709  $errors = $validator->getMessages();
710  $exception = new \Magento\Framework\Validator\Exception(
711  new Phrase(implode(PHP_EOL, $errors))
712  );
713  foreach ($errors as $errorMessage) {
714  $exception->addMessage(new \Magento\Framework\Message\Error($errorMessage));
715  }
716  throw $exception;
717  }
718  return $this;
719  }
720 
727  protected function _getValidatorBeforeSave()
728  {
729  if ($this->_validatorBeforeSave === null) {
730  $this->_validatorBeforeSave = $this->_createValidatorBeforeSave();
731  }
733  }
734 
741  protected function _createValidatorBeforeSave()
742  {
743  $modelRules = $this->_getValidationRulesBeforeSave();
744  $resourceRules = $this->_getResource()->getValidationRulesBeforeSave();
745  if (!$modelRules && !$resourceRules) {
746  return false;
747  }
748 
749  if ($modelRules && $resourceRules) {
750  $validator = new \Zend_Validate();
751  $validator->addValidator($modelRules);
752  $validator->addValidator($resourceRules);
753  } elseif ($modelRules) {
754  $validator = $modelRules;
755  } else {
756  $validator = $resourceRules;
757  }
758 
759  return $validator;
760  }
761 
767  protected function _getValidationRulesBeforeSave()
768  {
769  return null;
770  }
771 
778  public function getCacheTags()
779  {
780  $tags = false;
781  if ($this->_cacheTag) {
782  if ($this->_cacheTag === true) {
783  $tags = [];
784  } else {
785  if (is_array($this->_cacheTag)) {
786  $tags = $this->_cacheTag;
787  } else {
788  $tags = [$this->_cacheTag];
789  }
790  }
791  }
792  return $tags;
793  }
794 
800  public function cleanModelCache()
801  {
802  $tags = $this->getCacheTags();
803  if ($tags !== false) {
804  $this->_cacheManager->clean($tags);
805  }
806  return $this;
807  }
808 
814  public function afterSave()
815  {
816  $this->cleanModelCache();
817  $this->_eventManager->dispatch('model_save_after', ['object' => $this]);
818  $this->_eventManager->dispatch('clean_cache_by_tags', ['object' => $this]);
819  $this->_eventManager->dispatch($this->_eventPrefix . '_save_after', $this->_getEventData());
820  $this->updateStoredData();
821  return $this;
822  }
823 
833  public function delete()
834  {
835  $this->_getResource()->delete($this);
836  return $this;
837  }
838 
845  public function beforeDelete()
846  {
847  if (!$this->_actionValidator->isAllowed($this)) {
848  throw new \Magento\Framework\Exception\LocalizedException(
849  new \Magento\Framework\Phrase('Delete operation is forbidden for current area')
850  );
851  }
852 
853  $this->_eventManager->dispatch('model_delete_before', ['object' => $this]);
854  $this->_eventManager->dispatch($this->_eventPrefix . '_delete_before', $this->_getEventData());
855  $this->cleanModelCache();
856  return $this;
857  }
858 
864  public function afterDelete()
865  {
866  $this->_eventManager->dispatch('model_delete_after', ['object' => $this]);
867  $this->_eventManager->dispatch('clean_cache_by_tags', ['object' => $this]);
868  $this->_eventManager->dispatch($this->_eventPrefix . '_delete_after', $this->_getEventData());
869  $this->storedData = [];
870  return $this;
871  }
872 
878  public function afterDeleteCommit()
879  {
880  $this->_eventManager->dispatch('model_delete_commit_after', ['object' => $this]);
881  $this->_eventManager->dispatch($this->_eventPrefix . '_delete_commit_after', $this->_getEventData());
882  return $this;
883  }
884 
891  public function getResource()
892  {
893  return $this->_getResource();
894  }
895 
901  public function getEntityId()
902  {
903  return $this->_getData('entity_id');
904  }
905 
912  public function setEntityId($entityId)
913  {
914  return $this->setData('entity_id', $entityId);
915  }
916 
922  public function clearInstance()
923  {
924  $this->_clearReferences();
925  $this->_eventManager->dispatch($this->_eventPrefix . '_clear', $this->_getEventData());
926  $this->_clearData();
927  return $this;
928  }
929 
935  protected function _clearReferences()
936  {
937  return $this;
938  }
939 
945  protected function _clearData()
946  {
947  return $this;
948  }
949 
955  private function updateStoredData()
956  {
957  if (isset($this->_data)) {
958  $this->storedData = $this->_data;
959  } else {
960  $this->storedData = [];
961  }
962  return $this;
963  }
964 
970  public function getStoredData()
971  {
972  return $this->storedData;
973  }
974 
980  public function getEventPrefix()
981  {
982  return $this->_eventPrefix;
983  }
984 }
getData($key='', $index=null)
Definition: DataObject.php:119
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
$objectManager
Definition: bootstrap.php:17
$resource
Definition: bulk.php:12
__construct(\Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Model\ResourceModel\AbstractResource $resource=null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection=null, array $data=[])
$value
Definition: gender.phtml:16
_setResourceModel($resourceName, $collectionName=null)
$resourceModel
Definition: tablerates.php:10
beforeLoad($identifier, $field=null)
$properties
Definition: categories.php:26
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18
$errors
Definition: overview.phtml:9
if(!isset($_GET['name'])) $name
Definition: log.php:14
$element
Definition: element.phtml:12