获取objectManager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

DataObject是所有Model的基类

$row = new \Magento\Framework\DataObject();
$row->setData($key, $value);
$row->getData($key);
$row->hasData($key);
$row->unsetData();
$row->toXml();
$row->toJson();
$row->debug();

date


/* @var $localeDate \Magento\Framework\Stdlib\DateTime\TimezoneInterface */
$localeDate = $objectManager->create(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class);
$localeDate->date()->format('Y-m-d H:i:s');

Session

$session = $objectManager->get('Magento\Framework\Session\Storage');
$session->setXxxx($value);
$session->getXxxx();
$session->hasXxxx();
$session->unsXxxx();

cache

// save
$this->cache = $context->getCache();
$this->cache->save(\Zend_Json::encode($data), self::CACHE_PREFIX . $key, [], $lifeTime);// load
$jsonStr = $this->cache->load(self::CACHE_PREFIX . $cacheKey);
if (strlen($jsonStr)) {$this->cachedData = \Zend_Json::decode($jsonStr);
}// sample
$cache = $objectManager->get(\Magento\Framework\App\CacheInterface::class);
$cached = $cache->load($cacheKey);
if(strlen($cached)) {$data = unserialize($cached);
} else {$data = [];$product = $objectManager->create('Magento\Catalog\Model\ProductRepository')->getById($id);$row = new \Magento\Framework\DataObject();$row->setData($row->getData());$data []= $row;$cache->save(serialize($data), $cacheKey);
}

判断是否首页

// in action
if($this->_request->getRouteName() == 'cms' && $this->_request->getActionName() == 'index') {// is home
}

Registry 用于内部传递临时值

/* @var \Magento\Framework\Registry $coreRegistry */
$coreRegistry = $this->_objectManager->get('Magento\Framework\Registry');
// 存储值
$coreRegistry->register('current_category', $category);
// 提取值
$coreRegistry->registry('current_category');

获取当前店铺对象

$store = $objectManager->get( 'Magento\Store\Model\StoreManagerInterface' )->getStore();

提示信息

// \Magento\Framework\App\Action\Action::execute()
$this->messageManager->addSuccessMessage(__('You deleted the event.'));
$this->messageManager->addErrorMessage(__('You deleted the event.'));
return $this->_redirect ( $returnUrl );

log (support_report.log)

\Magento\Framework\App\ObjectManager::getInstance()->get( '\Psr\Log\LoggerInterface' )->addCritical( 'notice message', ['order_id' => $order_id,'item_id' => $item_id// ...]);

获取当前页面 URL

$currentUrl = $objectManager->get( 'Magento\Framework\UrlInterface' )->getCurrentUrl();

获取指定路由 URL

$url = $objectManager->get( 'Magento\Store\Model\StoreManagerInterface' )->getStore()->getUrl( 'xxx/xxx/xxx' );

block里的URL

// 首页地址
$block->getBaseUrl();
// 指定 route 地址
$block->getUrl( '[module]/[controller]/[action]' );
// 指定的静态文件地址
$block->getViewFileUrl( 'Magento_Checkout::cvv.png' );
$block->getViewFileUrl( 'images/loader-2.gif' );

获取所有website的地址

$storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
foreach($storeManager->getWebsites() as $website) {$store_id = $storeManager->getGroup($website->getDefaultGroupId())->getDefaultStoreId();$storeManager->getStore($store_id)->getBaseUrl();
}

获取module下的文件

/** @var \Magento\Framework\Module\Dir\Reader $reader */
$reader = $objectManager->get('Magento\Framework\Module\Dir\Reader');
$reader->getModuleDir('etc', 'Infinity_Project').'/di.xml';

获取资源路径

/* @var \Magento\Framework\View\Asset\Repository $asset */
$asset = $this->_objectManager->get( '\Magento\Framework\View\Asset\Repository' );
$asset->createAsset('Vendor_Module::js/script.js')->getPath();

文件操作

/* @var \Magento\Framework\Filesystem $fileSystem */
$fileSystem = $this->_objectManager->get('Magento\Framework\Filesystem');
$fileSystem->getDirectoryWrite('tmp')->copyFile($from, $to);
$fileSystem->getDirectoryWrite('tmp')->delete($file);
$fileSystem->getDirectoryWrite('tmp')->create($file);

文件上传

// 上传到media
$request = $this->getRequest ();
if($request->isPost()) {try{/* @var $uploader \Magento\MediaStorage\Model\File\Uploader */$uploader = $this->_objectManager->create('Magento\MediaStorage\Model\File\Uploader',['fileId' => 'personal_photos']);/* @var $filesystem \Magento\Framework\Filesystem */$filesystem = $this->_objectManager->get( 'Magento\Framework\Filesystem' );$dir = $filesystem->getDirectoryRead( \Magento\Framework\App\Filesystem\DirectoryList::UPLOAD )->getAbsolutePath();$fileName = time().'.'.$uploader->getFileExtension();$uploader->save($dir, $fileName);$fileUrl = 'pub/media/upload/'.$fileName;} catch(Exception $e) {// 未上传}
}
// 上传到tmp
/* @var \Magento\Framework\App\Filesystem\DirectoryList $directory */
$directory = $this->_objectManager->get('Magento\Framework\App\Filesystem\DirectoryList');
/* @var \Magento\Framework\File\Uploader $uploader */
$uploader = $this->_objectManager->create('Magento\Framework\File\Uploader', array('fileId' => 'file1'));
$uploader->setAllowedExtensions(array('csv'));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$result = $uploader->save($directory->getPath($directory::TMP));
$directory->getPath($directory::TMP).$result['file'];

产品缩略图

$imageHelper = $objectManager->get( 'Magento\Catalog\Helper\Image' );
$productImage = $imageHelper->init( $product, 'category_page_list' )->constrainOnly( FALSE )->keepAspectRatio( TRUE )->keepFrame( FALSE )->resize( 400 )->getUrl();

缩略图

$imageFactory = $objectManager->get( 'Magento\Framework\Image\Factory' );
$imageAdapter = $imageFactory->create($path);
$imageAdapter->resize($width, $height);
$imageAdapter->save($savePath);

产品属性

/* @var \Magento\Catalog\Model\ProductRepository $product */
$product = $objectManager->create('Magento\Catalog\Model\ProductRepository')->getById($id);
// print price
/* @var \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency */
$priceCurrency = $objectManager->get('Magento\Framework\Pricing\PriceCurrencyInterface');
$priceCurrency->format($product->getData('price'));
// print option value
$product->getResource()->getAttribute('color')->getDefaultFrontendLabel();
$product->getAttributeText('color');
// all options
$this->helper('Magento\Catalog\Helper\Output')->productAttribute($product, $product->getData('color'), 'color');
$product->getResource()->getAttribute('color')->getSource()->getAllOptions();
// save attribute
$product->setWeight(1.99)->getResource()->saveAttribute($product, 'weight');
// 库存
$stockItem = $this->stockRegistry->getStockItem($productId, $product->getStore()->getWebsiteId());
$minimumQty = $stockItem->getMinSaleQty();
// Configurable Product 获取父级产品ID
$parentIds = $this->objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable')->getParentIdsByChild($productId);
$parentId = array_shift($parentIds);
// Configurable Product 获取子级产品ID
$childIds = $this->objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable')->getChildrenIds($parentId);
// 获取Configurable Product的子产品Collection
$collection = $this->objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable')->getUsedProducts($product);
// 判断是否Configurable Product
if ($_product->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE);

购物车中的所有产品

/* @var \Magento\Checkout\Model\Session $checkoutSession */
$checkoutSession = $objectManager->get('Magento\Checkout\Model\Session');
foreach($checkoutSession->getQuote()->getItems() as $item) {/* @var \Magento\Quote\Model\Quote\Item $item */echo $item->getProduct()->getName().'<br/>';
}

获取类型配置

$eavConfig->getAttribute('catalog_product', 'price');
$eavConfig->getEntityType('catalog_product');

获取 EAV 属性所有可选项

/* @var $objectManager \Magento\Framework\App\ObjectManager */
$eavConfig = $objectManager->get( '\Magento\Eav\Model\Config' );
$options = $eavConfig->getAttribute( '[entity_type]', '[attribute_code]' )->getFrontend()->getSelectOptions();
//或者
/* @var $objectManager \Magento\Framework\App\ObjectManager */
$options = $objectManager->create( 'Magento\Eav\Model\Attribute' )->load( '[attribute_code]', 'attribute_code' )->getSource()->getAllOptions( false );

获取config.xml与system.xml里的参数

$this->_scopeConfig = $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface');
// 语言代码
$this->_scopeConfig->getValue('general/locale/code', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);

客户唯一属性验证

if($customer instanceof \Magento\Customer\Model\Customer) {/* @var \Magento\Customer\Model\Attribute $attribute */foreach($customer->getAttributes() as $attribute) {if($attribute->getIsUnique()) {if (!$attribute->getEntity()->checkAttributeUniqueValue($attribute, $customer)) {$label = $attribute->getFrontend()->getLabel();throw new \Magento\Framework\Exception\LocalizedException(__('The value of attribute "%1" must be unique.', $label));}}}
}

读取design view.xml

<vars module="Vendor_Module"><var name="var1">value1</var>
</vars>
/* @var \Magento\Framework\Config\View $viewConfig */
$viewConfig = $objectManager->get('Magento\Framework\Config\View');
$viewConfig->getVarValue('Vendor_Module', 'var1');

获取邮件模板

虽然叫邮件模板,但也可以用于需要后台编辑模板的程序

// template id, 通常在email_templates.xml定义。如果是在后台加的email template,需要换成template的记录ID,例如90
$identifier = 'contact_email_email_template';
/* @var \Magento\Framework\Mail\TemplateInterface $templateFactory */
$templateFactory = $this->_objectManager->create('Magento\Framework\Mail\TemplateInterface',['data' => ['template_id' => $identifier]]
);
// 模板变量,取决于phtml或后台email template的内容
$dataObject = new \Magento\Framework\DataObject();
$dataObject->setData('name', 'william');
// 决定模板变量取值区域,例如像{{layout}}这样的标签,如果取不到值可以试试把area设为frontend
$templateFactory->setOptions(['area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE,'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID
]);
$templateFactory->setVars(['data' => $dataObject]);
return $templateFactory->processTemplate();

内容返回

$this->resultFactory = $this->_objectManager->create('Magento\Framework\Controller\Result\RawFactory');
/* @var \Magento\Framework\Controller\Result\Raw $result */
$result = $this->resultFactory->create();
$result->setContents('hello world');
return $result;
$this->resultFactory = $this->_objectManager->create('Magento\Framework\Controller\Result\JsonFactory');
/* @var \Magento\Framework\Controller\Result\Json $result */
$result = $this->resultFactory->create();
$result->setData(['message' => 'hellog world']);
return $result;

HTTP文件

$this->_fileFactory = $this->_objectManager->create('Magento\Framework\App\Response\Http\FileFactory');
$this->_fileFactory->create('invoice' . $date . '.pdf',$pdf->render(),DirectoryList::VAR_DIR,'application/pdf'
);

切换货币与语言

$currencyCode = 'GBP';
/* @var \Magento\Store\Model\Store $store */
$store = $this->_objectManager->get('Magento\Store\Model\Store');
$store->setCurrentCurrencyCode($currencyCode);$storeCode = 'uk';
/* @var \Magento\Store\Api\StoreRepositoryInterface $storeRepository */
$storeRepository = $this->_objectManager->get('Magento\Store\Api\StoreRepositoryInterface');
/* @var \Magento\Store\Model\StoreManagerInterface $storeManager */
$storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');
/* @var \Magento\Store\Api\StoreCookieManagerInterface $storeCookieManager */
$storeCookieManager = $this->_objectManager->get('Magento\Store\Api\StoreCookieManagerInterface');
/* @var \Magento\Framework\App\Http\Context $httpContext */
$httpContext = $this->_objectManager->get('Magento\Framework\App\Http\Context');
$defaultStoreView = $storeManager->getDefaultStoreView();
$store = $storeRepository->getActiveStoreByCode($storeCode);
$httpContext->setValue(\Magento\Store\Model\Store::ENTITY, $store->getCode(), $defaultStoreView->getCode());
$storeCookieManager->setStoreCookie($store);$this->getResponse()->setRedirect($this->_redirect->getRedirectUrl());

Profiler

\Magento\Framework\Profiler::start('CONFIGURABLE:' . __METHOD__,['group' => 'CONFIGURABLE', 'method' => __METHOD__]
);
\Magento\Framework\Profiler::stop('CONFIGURABLE:' . __METHOD__);

HTML表单元素

日历控件

$block->getLayout()->createBlock('Magento\Framework\View\Element\Html\Date')->setName('date')->setId('date')->setClass('date')->setDateFormat('M/d/yy')->setImage($block->getViewFileUrl('Magento_Theme::calendar.png'))->setExtraParams('data-validate="{required:true}"')->toHtml();

select控件

$block->getLayout()->createBlock('Magento\Framework\View\Element\Html\Select')->setName('sel1')->setId('sel1')->setClass('select')->addOption('value', 'label')->setValue($default)->setExtraParams('data-validate="{required:true}"')->toHtml();

magento2 常用代码相关推荐

  1. pytorch常用代码

    20211228 https://mp.weixin.qq.com/s/4breleAhCh6_9tvMK3WDaw 常用代码段 本文代码基于 PyTorch 1.x 版本,需要用到以下包: impo ...

  2. 一、PyTorch Cookbook(常用代码合集)

    PyTorch Cookbook(常用代码合集) 原文链接:https://mp.weixin.qq.com/s/7at6y2NcYaxGGN8syxlccA 谢谢作者的付出.

  3. GitHub上7000+ Star的Python常用代码合集

    作者 | 二胖并不胖 来源 | 大数据前沿(ID:bigdataqianyan) 今天二胖给大家介绍一个由一个国外小哥用好几年时间维护的Python代码合集.简单来说就是,这个程序员小哥在几年前开始保 ...

  4. 收藏!PyTorch常用代码段合集

    ↑↑↑关注后"星标"Datawhale 每日干货 & 每月组队学习,不错过 Datawhale干货 作者:Jack Stark,来源:极市平台 来源丨https://zhu ...

  5. PyTorch常用代码段合集

    ↑ 点击蓝字 关注视学算法 作者丨Jack Stark@知乎 来源丨https://zhuanlan.zhihu.com/p/104019160 极市导读 本文是PyTorch常用代码段合集,涵盖基本 ...

  6. JavaScript常用代码

    在这存一下JavaScript常用代码: 1.封装输出 1 var log = function() { 2 console.log.apply(console, arguments) 3 } 4 5 ...

  7. javascript常用代码大全

    http://caibaojian.com/288.html     原文链接 jquery选中radio//如果之前有选中的,则把选中radio取消掉 $("#tj_cat .pro_ca ...

  8. mysql四列数据表代码_MySQL数据库常用代码

    MySQL数据库常用代码启动数据库服务:[ net Start MySQL ] 使用命令登录:[ Mysql -h localhost -u root -p] 关闭数据库服务: [net stop m ...

  9. Lambda表达式常用代码示例

    Lambda表达式常用代码示例 2017-10-24 目录 1 Lambda表达式是什么 2 Lambda表达式语法 3 函数式接口是什么   3.1 常用函数式接口 4 Lambdas和Stream ...

最新文章

  1. [LeetCode] Search Insert Position 搜索插入位置
  2. 区块链BaaS云服务(25)边界智能 IRITA平台
  3. 天才基本法_强推|高人气合集狙击蝴蝶天才基本法春日玛格丽特难哄
  4. Learning Attention-based Embeddings for Relation Prediction in Knowledge Graphs Deepak
  5. docker mysql日志_面试官问:了解Mysql主从复制原理么?我呵呵一笑
  6. Unity面试题精选(6)
  7. 常见面试算法:k-近邻算法原理与python案例实现
  8. 拓端tecdat|python卷积神经网络人体图像识别
  9. C++ 迭代器是指针吗
  10. 如何查询redhat的版本信息
  11. 服务器远程桌面日志,Windows记录远程桌面3389登录日志
  12. c语言timer linux 回调函数_SetTimer 与 回调函数
  13. obs点开始推流显示无法连接服务器,前沿科技资讯:OBS Studio推流连接失败如何办 OBS推流失败的正确解决方法...
  14. 「数据结构 | 链表」单链表、双向链表节点操作演示动画
  15. Android TV 开发简介
  16. “古董级” 诺基亚功能机跑Linux是怎样的画风?
  17. 计算三维空间中直线和三角形的交点
  18. 百度智能产品初现“卡组效应”:矩阵优势究竟对硬件市场有多重要
  19. 阿里重投内容电商,VR技术会成为马云的杀手锏吗?
  20. ES大量数据条件检索准确性问题

热门文章

  1. 这个严重漏洞可被滥用于破坏交通信号灯系统
  2. 『总结』CSS/CSS3常用样式与web移动端资源
  3. Linux 6.4 partprobe出现warning问题
  4. 各个 Maven仓库 镜像(包括国内)
  5. 差分约束系统 POJ 3169 Layout
  6. 别以为真懂Openstack: 虚拟机创建的50个步骤和100个知识点(1)
  7. 3389远程连接问题的一个解决办法
  8. Python MySQL(MySQLdb)
  9. 用Python实现应用Last-Modified和ETag避免下载重复内容
  10. cmake笔记(1)