部分系统常用方法:
调用CMS静态块:
<?php echo $this->getLayout() ->createBlock('MagentoCmsBlockBlock') ->setBlockId('your_block_identifier') ->toHtml(); ?>
在CMS内容中显示CMS静态块:
{{block class="Magento\Cms\Block\Block" block_id="block_identifier"}}
以XML显示CMS静态块:
<referenceContainer name="content"> <block class="MagentoCmsBlockBlock" name="block_identifier"> <arguments> <argument name="block_id" xsi:type="string">block_identifier</argument> </arguments> </block> </referenceContainer>
在Phtml内调用其它Phtml块:
<?php echo $this->getLayout()->createBlock("MagentoThemeBlockHtml[$Block_Class]")->setTemplate("Magento_Theme::html/[$name].phtml")->toHtml() ?>
管理员和用户访问令牌 :
|- 获取客户令牌:【POST】 localhost/rest//V1/integration/customer/token 时效(Stores > Settings > Configuration > Services > OAuth > Access Token Expiration):一个小时
|- 获取管理员令牌 : 【POST】 localhost/rest/V1/integration/admin/token 时效(Stores > Settings > Configuration > Services > OAuth > Access Token Expiration):四个小时
-测试API命令,如不能通过,请检查 admin_usernameadminpassword:
curl -X POST "http://localhost/index.php/rest/V1/integration/admin/token" -H "Content-Type:application/json" -d '{"username":"username", "password":"password!"}'
集成令牌:在后台设置 System > Extensions > Integrations Add New Integration->Save->Activate ; 激活完成取 Access Token 作为 <authentication token>;
|- Authorization: Bearer <authentication token>
curl -X GET "localhost/index.php/rest/V1/customers/9" -H "Authorization: Bearer k4ulh24rmq*****6q1txln2v0ghb"
获取objectManager
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
用这个objectManager方法能调用所有类,无需在构造函数里定义。
DataObject是所有Model的基类
$row = new MagentoFrameworkDataObject(); $row->setData($key, $value); $row->getData($key); $row->hasData($key); $row->unsetData(); $row->toXml(); $row->toJson(); $row->debug();
Session
$session = $objectManager->get('MagentoFrameworkSessionStorage'); $session->setXxxx($value); $session->getXxxx(); $session->hasXxxx(); $session->unsXxxx();
cache
// save $this->cache = $context->getCache(); $this->cache->save(end_Json::encode($data), self::CACHE_PREFIX . $key, [], $lifeTime); // load $jsonStr = $this->cache->load(self::CACHE_PREFIX . $cacheKey); if (strlen($jsonStr)) { $this->cachedData = end_Json::decode($jsonStr); }
判断是否首页
// in action if($this->_request->getRouteName() == 'cms' && $this->_request->getActionName() == 'index') { // is home }
Registry 用于内部传递临时值
/* @var MagentoFrameworkRegistry $coreRegistry */ $coreRegistry = $this->_objectManager->get('MagentoFrameworkRegistry'); // 存储值 $coreRegistry->register('current_category', $category); // 提取值 $coreRegistry->registry('current_category');
获取当前店铺对象
$store = $objectManager->get( 'MagentoStoreModelStoreManagerInterface' )->getStore();
提示信息
// MagentoFrameworkAppActionAction::execute() $this->messageManager->addSuccessMessage(__('You deleted the event.')); $this->messageManager->addErrorMessage(__('You deleted the event.')); return $this->_redirect ( $returnUrl ); log (support_report.log) MagentoFrameworkAppObjectManager::getInstance() ->get( 'PsrLogLoggerInterface' )->addCritical( 'notice message', [ 'order_id' => $order_id, 'item_id' => $item_id // ... ]);
保存customer自定义属性
比如我新建了一个customer属性叫new_register_promocode
。
$customer = $objectManager->get('MagentoCustomerModelCustomer')->load($customer->getId()); $customerDataModel = $customer->getDataModel(); $customerDataModel->setCustomAttribute('new_register_promocode',null); $customer->updateData($customerDataModel); $customer->save();
获取当前页面 URL
$currentUrl = $objectManager->get( 'MagentoFrameworkUrlInterface' )->getCurrentUrl();
获取指定路由 URL
$url = $objectManager->get( 'MagentoStoreModelStoreManagerInterface' )->getStore()->getUrl( 'xxx/xxx/xxx' );
获取pub/media的URL
$url = $objectManager->get('MagentoStoreModelStoreManagerInterface')->getStore()->getBaseUrl('media');
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('MagentoStoreModelStoreManagerInterface'); foreach($storeManager->getWebsites() as $website) { $store_id = $storeManager->getGroup($website->getDefaultGroupId())->getDefaultStoreId(); $storeManager->getStore($store_id)->getBaseUrl(); }
获取module下的文件
/** @var MagentoFrameworkModuleDirReader $reader */ $reader = $objectManager->get('MagentoFrameworkModuleDirReader'); $reader->getModuleDir('etc', 'Infinity_Project').'/di.xml';
获取资源路径
/* @var MagentoFrameworkViewAssetRepository $asset */ $asset = $this->_objectManager->get( 'MagentoFrameworkViewAssetRepository' ); $asset->createAsset('Vendor_Module::js/script.js')->getPath();
文件操作
/* @var MagentoFrameworkFilesystem $fileSystem */ $fileSystem = $this->_objectManager->get('MagentoFrameworkFilesystem'); $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 MagentoMediaStorageModelFileUploader */ $uploader = $this->_objectManager->create( 'MagentoMediaStorageModelFileUploader', ['fileId' => 'file'] ); /* @var $filesystem MagentoFrameworkFilesystem */ $filesystem = $this->_objectManager->get( 'MagentoFrameworkFilesystem' ); $dir = $filesystem->getDirectoryRead( MagentoFrameworkAppFilesystemDirectoryList::UPLOAD )->getAbsolutePath(); $fileName = time().'.'.$uploader->getFileExtension(); $uploader->save($dir, $fileName); $fileUrl = 'pub/media/upload/'.$fileName; } catch(Exception $e) { // 未上传 } } // 上传到tmp /* @var MagentoFrameworkAppFilesystemDirectoryList $directory */ $directory = $this->_objectManager->get('MagentoFrameworkAppFilesystemDirectoryList'); /* @var MagentoFrameworkFileUploader $uploader */ $uploader = $this->_objectManager->create('MagentoFrameworkFileUploader', 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( 'MagentoCatalogHelperImage' ); $productImage = $imageHelper->init( $product, 'category_page_list' ) ->constrainOnly( FALSE ) ->keepAspectRatio( TRUE ) ->keepFrame( FALSE ) ->resize( 400 ) ->getUrl();
缩略图
$imageFactory = $objectManager->get( 'MagentoFrameworkImageFactory' ); $imageAdapter = $imageFactory->create($path); $imageAdapter->resize($width, $height); $imageAdapter->save($savePath);
产品属性
/* @var MagentoCatalogModelProductRepository $product */ $product = $objectManager->create('MagentoCatalogModelProductRepository')->getById($id); // print price /* @var MagentoFrameworkPricingPriceCurrencyInterface $priceCurrency */ $priceCurrency = $objectManager->get('MagentoFrameworkPricingPriceCurrencyInterface'); $priceCurrency->format($product->getData('price')); // print option value $product->getResource()->getAttribute('color')->getDefaultFrontendLabel(); $product->getAttributeText('color'); // all options $this->helper('MagentoCatalogHelperOutput')->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('MagentoConfigurableProductModelProductTypeConfigurable') ->getParentIdsByChild($productId); $parentId = array_shift($parentIds); // Configurable Product 获取子级产品ID $childIds = $this->objectManager->get('MagentoConfigurableProductModelProductTypeConfigurable') ->getChildrenIds($parentId); // 获取Configurable Product的子产品Collection $collection = $this->objectManager->get('MagentoConfigurableProductModelProductTypeConfigurable') ->getUsedProducts($product); // 判断是否Configurable Product if ($_product->getTypeId() == MagentoConfigurableProductModelProductTypeConfigurable::TYPE_CODE); //获取自定义产品属性 (比如新建了一个产品属性叫`Activity`) $product = $objectManager->create('MagentoCatalogModelProductRepository')->getById($id); var_dump($product->getActivity());
购物车中的所有产品
/* @var MagentoCheckoutModelSession $checkoutSession */ $checkoutSession = $objectManager->get('MagentoCheckoutModelSession'); foreach($checkoutSession->getQuote()->getItems() as $item) { /* @var MagentoQuoteModelQuoteItem $item */ echo $item->getProduct()->getName().'<br/>'; }
获取类型配置
$eavConfig->getAttribute('catalog_product', 'price'); $eavConfig->getEntityType('catalog_product');
获取 EAV 属性所有可选项
/* @var $objectManager MagentoFrameworkAppObjectManager */ $eavConfig = $objectManager->get( 'MagentoEavModelConfig' ); $options = $eavConfig->getAttribute( '[entity_type]', '[attribute_code]' ) ->getFrontend()->getSelectOptions(); //或者 /* @var $objectManager MagentoFrameworkAppObjectManager */ $options = $objectManager->create( 'MagentoEavModelAttribute' ) ->load( '[attribute_code]', 'attribute_code' )->getSource() ->getAllOptions( false );
获取config.xml与system.xml里的参数
$this->_scopeConfig = $this->_objectManager->create('MagentoFrameworkAppConfigScopeConfigInterface'); // 语言代码 $this->_scopeConfig->getValue('general/locale/code', MagentoStoreModelScopeInterface::SCOPE_STORE, $storeId);
客户唯一属性验证
if($customer instanceof MagentoCustomerModelCustomer) { /* @var MagentoCustomerModelAttribute $attribute */ foreach($customer->getAttributes() as $attribute) { if($attribute->getIsUnique()) { if (!$attribute->getEntity()->checkAttributeUniqueValue($attribute, $customer)) { $label = $attribute->getFrontend()->getLabel(); throw new MagentoFrameworkExceptionLocalizedException( __('The value of attribute "%1" must be unique.', $label) ); } } } }
读取design view.xml
<vars module="Vendor_Module"> <var name="var1">value1</var> </vars> /* @var MagentoFrameworkConfigView $viewConfig */ $viewConfig = $objectManager->get('MagentoFrameworkConfigView'); $viewConfig->getVarValue('Vendor_Module', 'var1');
获取邮件模板
虽然叫邮件模板,但也可以用于需要后台编辑模板的程序
// template id, 通常在email_templates.xml定义。如果是在后台加的email template,需要换成template的记录ID,例如90 $identifier = 'contact_email_email_template'; /* @var MagentoFrameworkMailTemplateInterface $templateFactory */ $templateFactory = $this->_objectManager->create( 'MagentoFrameworkMailTemplateInterface', ['data' => ['template_id' => $identifier]] ); // 模板变量,取决于phtml或后台email template的内容 $dataObject = new MagentoFrameworkDataObject(); $dataObject->setData('name', 'william'); // 决定模板变量取值区域,例如像{{layout}}这样的标签,如果取不到值可以试试把area设为frontend $templateFactory->setOptions([ 'area' => MagentoBackendAppAreaFrontNameResolver::AREA_CODE, 'store' => MagentoStoreModelStore::DEFAULT_STORE_ID ]); $templateFactory->setVars(['data' => $dataObject]); return $templateFactory->processTemplate();
内容返回
$this->resultFactory = $this->_objectManager->create('MagentoFrameworkControllerResultRawFactory'); /* @var MagentoFrameworkControllerResultRaw $result */ $result = $this->resultFactory->create(); $result->setContents('hello world'); return $result; $this->resultFactory = $this->_objectManager->create('MagentoFrameworkControllerResultJsonFactory'); /* @var MagentoFrameworkControllerResultJson $result */ $result = $this->resultFactory->create(); $result->setData(['message' => 'hellog world']); return $result;
HTTP文件
$this->_fileFactory = $this->_objectManager->create('MagentoFrameworkAppResponseHttpFileFactory'); $this->_fileFactory->create( 'invoice' . $date . '.pdf', $pdf->render(), DirectoryList::VAR_DIR, 'application/pdf' );
切换货币与语言
$currencyCode = 'GBP'; /* @var MagentoStoreModelStore $store */ $store = $this->_objectManager->get('MagentoStoreModelStore'); $store->setCurrentCurrencyCode($currencyCode); $storeCode = 'uk'; /* @var MagentoStoreApiStoreRepositoryInterface $storeRepository */ $storeRepository = $this->_objectManager->get('MagentoStoreApiStoreRepositoryInterface'); /* @var MagentoStoreModelStoreManagerInterface $storeManager */ $storeManager = $this->_objectManager->get('MagentoStoreModelStoreManagerInterface'); /* @var MagentoStoreApiStoreCookieManagerInterface $storeCookieManager */ $storeCookieManager = $this->_objectManager->get('MagentoStoreApiStoreCookieManagerInterface'); /* @var MagentoFrameworkAppHttpContext $httpContext */ $httpContext = $this->_objectManager->get('MagentoFrameworkAppHttpContext'); $defaultStoreView = $storeManager->getDefaultStoreView(); $store = $storeRepository->getActiveStoreByCode($storeCode); $httpContext->setValue(MagentoStoreModelStore::ENTITY, $store->getCode(), $defaultStoreView->getCode()); $storeCookieManager->setStoreCookie($store); $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl());
Profiler
MagentoFrameworkProfiler::start( 'CONFIGURABLE:' . __METHOD__, ['group' => 'CONFIGURABLE', 'method' => __METHOD__] ); MagentoFrameworkProfiler::stop('CONFIGURABLE:' . __METHOD__);
HTML表单元素
日历控件
$block->getLayout()->createBlock('MagentoFrameworkViewElementHtmlDate') ->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('MagentoFrameworkViewElementHtmlSelect') ->setName('sel1') ->setId('sel1') ->setClass('select') ->addOption('value', 'label') ->setValue($default) ->setExtraParams('data-validate="{required:true}"') ->toHtml();
获取产品属性的label
比如产品属性color
,我后台设置了中文label为颜色
。
用下面的代码可以获取属性color
的label
$_attributeLabel = $_product->getResource()->getAttribute($_code)->getStoreLabel();
获取产品属性option的label
比如产品属性color,是dropdown类型的,某个option值为XL.
前台直接$product->getColor(),得到的是个数字,而不是我设置的'XL'。
用下面的代码可以获取option的label
$optionLabel = $_product->getResource()->getAttribute('your_attribute_code')->getFrontend()->getValue($_product);
获取订单里的产品
$allItems = $order->getAllItems(); foreach ($allItems as $item) { if ($item->getParentItem() ) { //忽略掉可配置产品的子产品 continue; } $qty = (int)$item->getQty()*1; $name = $item->getProduct()->getName(); }
获取产品的catalog price rule
/** * @param $productId * @param $customerGroupId * @return mixed */ public function getCatalogPriceRuleFromProduct($productId, $customerGroupId) { /** * @var MagentoCatalogModelProductFactory */ $product = $this->_objectManager->create('MagentoCatalogModelProductFactory')->create()->load($productId); $storeId = $product->getStoreId(); $store = $this->_store_manager->getStore($storeId); $websiteId = $store->getWebsiteId(); /** * @var MagentoFrameworkStdlibDateTimeDateTime */ $date = $this->_objectManager->create('MagentoFrameworkStdlibDateTimeDateTime'); $dateTs = $date->gmtDate(); /** * @var MagentoCatalogRuleModelResourceModelRule */ $resource = $this->_objectManager->create('MagentoCatalogRuleModelResourceModelRule'); $rules = $resource->getRulesFromProduct($dateTs, $websiteId, $customerGroupId, $productId); return $rules; }
获得实际的折扣金额:
/* * @var MagentoCatalogRuleModelRuleFactory */ $rule = $this->_objectManager->create('MagentoCatalogRuleModelRuleFactory')->create(); $discountAmount = $rule->calcProductPriceRule($product,$product->getPrice());
获取当前页面的控制器/action等
在phtml
和controller
里调用
echo $controllerName = $this->getRequest()->getControllerName(); echo $actionName = $this->getRequest()->getActionName(); echo $routeName = $this->getRequest()->getRouteName(); echo $moduleName = $this->getRequest()->getModuleName();
过滤处理可视化编辑器内容
主要把标签和变量转换。
比如{{store}}
,{{view}}
,{{media}}
等
$description = $product->getDescription(); $_templateProcessor = $this->_objectManager->get('MagentoCatalogHelperData')->getPageTemplateProcessor(); $description = $_templateProcessor->filter($description);