首页 > 其他 > 详细

解决方案-定期更新

时间:2020-03-19 22:38:31      阅读:59      评论:0      收藏:0      [点我收藏+]

 

部分系统常用方法:

 

获取objectManager

技术分享图片
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
View Code

用这个objectManager方法能调用所有类,无需在构造函数里定义。

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();
View Code

Session

技术分享图片
$session = $objectManager->get(‘Magento\Framework\Session\Storage‘);
$session->setXxxx($value);
$session->getXxxx();
$session->hasXxxx();
$session->unsXxxx();
View Code

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);
}
View Code

判断是否首页

技术分享图片
// in action
if($this->_request->getRouteName() == ‘cms‘ && $this->_request->getActionName() == ‘index‘) {
    // is home
}
View Code

Registry 用于内部传递临时值

技术分享图片
/* @var \Magento\Framework\Registry $coreRegistry */
$coreRegistry = $this->_objectManager->get(‘Magento\Framework\Registry‘);
// 存储值
$coreRegistry->register(‘current_category‘, $category);
// 提取值
$coreRegistry->registry(‘current_category‘);
View Code

获取当前店铺对象

技术分享图片
$store = $objectManager->get( ‘Magento\Store\Model\StoreManagerInterface‘ )->getStore();
View Code

提示信息

技术分享图片
// \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
        // ...
    ]);
View Code

保存customer自定义属性

比如我新建了一个customer属性叫new_register_promocode

技术分享图片
$customer = $objectManager->get(‘\Magento\Customer\Model\Customer‘)->load($customer->getId());
                $customerDataModel = $customer->getDataModel();
                $customerDataModel->setCustomAttribute(‘new_register_promocode‘,null);
                $customer->updateData($customerDataModel);
                $customer->save();
View Code

获取当前页面 URL

技术分享图片
$currentUrl = $objectManager->get( ‘Magento\Framework\UrlInterface‘ )->getCurrentUrl();
View Code

获取指定路由 URL

技术分享图片
$url = $objectManager->get( ‘Magento\Store\Model\StoreManagerInterface‘ )->getStore()->getUrl( ‘xxx/xxx/xxx‘ );
View Code

获取pub/media的URL

技术分享图片
$url = $objectManager->get(‘Magento\Store\Model\StoreManagerInterface‘)->getStore()->getBaseUrl(‘media‘);
View Code

输出: http://xxx.com/pub/media/

block里的URL

技术分享图片
// 首页地址
$block->getBaseUrl();
// 指定 route 地址
$block->getUrl( ‘[module]/[controller]/[action]‘ );
// 指定的静态文件地址
$block->getViewFileUrl( ‘Magento_Checkout::cvv.png‘ );
$block->getViewFileUrl( ‘images/loader-2.gif‘ );
View Code

获取所有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();
}
View Code

获取module下的文件

技术分享图片
/** @var \Magento\Framework\Module\Dir\Reader $reader */
$reader = $objectManager->get(‘Magento\Framework\Module\Dir\Reader‘);
$reader->getModuleDir(‘etc‘, ‘Infinity_Project‘).‘/di.xml‘;
View Code

获取资源路径

技术分享图片
/* @var \Magento\Framework\View\Asset\Repository $asset */
$asset = $this->_objectManager->get( ‘\Magento\Framework\View\Asset\Repository‘ );
$asset->createAsset(‘Vendor_Module::js/script.js‘)->getPath();
View Code

文件操作

技术分享图片
/* @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);
View Code

文件上传

技术分享图片
// 上传到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‘ => ‘file‘]
        );
        /* @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‘];
View Code

产品缩略图

技术分享图片
$imageHelper = $objectManager->get( ‘Magento\Catalog\Helper\Image‘ );
$productImage = $imageHelper->init( $product, ‘category_page_list‘ )
  ->constrainOnly( FALSE )
  ->keepAspectRatio( TRUE )
  ->keepFrame( FALSE )
  ->resize( 400 )
  ->getUrl();
View Code

缩略图

技术分享图片
$imageFactory = $objectManager->get( ‘Magento\Framework\Image\Factory‘ );
$imageAdapter = $imageFactory->create($path);
$imageAdapter->resize($width, $height);
$imageAdapter->save($savePath);
View Code

产品属性

技术分享图片
/* @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);

//获取自定义产品属性 (比如新建了一个产品属性叫`Activity`)
$product = $objectManager->create(‘Magento\Catalog\Model\ProductRepository‘)->getById($id);
var_dump($product->getActivity());
View 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/>‘;
}
View Code

获取类型配置

技术分享图片
$eavConfig->getAttribute(‘catalog_product‘, ‘price‘);
$eavConfig->getEntityType(‘catalog_product‘);
View Code

获取 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 );
View Code

获取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);
View Code

客户唯一属性验证

技术分享图片
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)
                );
            }
        }
    }
}
View Code

读取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‘);
View Code

获取邮件模板

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

技术分享图片
// 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();
View Code

内容返回

技术分享图片
$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;
View Code

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‘
);
View Code

切换货币与语言

技术分享图片
$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());
View Code

Profiler

技术分享图片
\Magento\Framework\Profiler::start(
    ‘CONFIGURABLE:‘ . __METHOD__,
    [‘group‘ => ‘CONFIGURABLE‘, ‘method‘ => __METHOD__]
);
\Magento\Framework\Profiler::stop(‘CONFIGURABLE:‘ . __METHOD__);
View Code

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();

获取产品属性的label

比如产品属性color,我后台设置了中文label为颜色
用下面的代码可以获取属性colorlabel

$_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);
View Code

获取订单里的产品

技术分享图片
$allItems = $order->getAllItems();
foreach ($allItems as $item) {
    if ($item->getParentItem()
            ) {
                //忽略掉可配置产品的子产品
                continue;
            }
            $qty = (int)$item->getQty()*1;
            $name = $item->getProduct()->getName();
   }
View Code

获取产品的catalog price rule

技术分享图片
/**
 * @param $productId
 * @param $customerGroupId
 * @return mixed
 */
public function getCatalogPriceRuleFromProduct($productId, $customerGroupId)
{
    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    $product = $this->_objectManager->create(‘\Magento\Catalog\Model\ProductFactory‘)->create()->load($productId);

    $storeId = $product->getStoreId();
    $store = $this->_store_manager->getStore($storeId);
    $websiteId = $store->getWebsiteId();
    /**
     * @var \Magento\Framework\Stdlib\DateTime\DateTime
     */
    $date = $this->_objectManager->create(‘\Magento\Framework\Stdlib\DateTime\DateTime‘);
    $dateTs = $date->gmtDate();

    /**
     * @var \Magento\CatalogRule\Model\ResourceModel\Rule
     */
    $resource = $this->_objectManager->create(‘\Magento\CatalogRule\Model\ResourceModel\Rule‘);

    $rules = $resource->getRulesFromProduct($dateTs, $websiteId, $customerGroupId, $productId);

    return $rules;
}
View Code

获得实际的折扣金额:

技术分享图片
/*
* @var \Magento\CatalogRule\Model\RuleFactory
 */
$rule = $this->_objectManager->create(‘\Magento\CatalogRule\Model\RuleFactory‘)->create();
$discountAmount = $rule->calcProductPriceRule($product,$product->getPrice());
View Code

获取当前页面的控制器/action等

phtmlcontroller里调用

技术分享图片
echo $controllerName = $this->getRequest()->getControllerName();
echo $actionName = $this->getRequest()->getActionName();
echo $routeName = $this->getRequest()->getRouteName();
echo $moduleName = $this->getRequest()->getModuleName(); 
View Code

过滤处理可视化编辑器内容

主要把标签和变量转换。
比如{{store}},{{view}},{{media}}

技术分享图片
$description = $product->getDescription();
$_templateProcessor = $this->_objectManager->get(‘Magento\Catalog\Helper\Data‘)->getPageTemplateProcessor();
$description = $_templateProcessor->filter($description);
View Code

 





解决方案-定期更新

原文:https://www.cnblogs.com/q1104460935/p/12527496.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!