magento2 常用代码

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

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$this->date = $objectManager->get(\Magento\Framework\Stdlib\DateTime\DateTime::class);
$this->datetimezone = $objectManager->get(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class);
$this->currentTimestamp = $this->datetimezone->scopeTimeStamp();

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

 

转发:https://segmentfault.com/a/1190000005154774

 

转载于:https://my.oschina.net/ganfanghua/blog/2873735

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Magento奖励积分-Magento 2的奖励积分 Magento奖励积分-Magento 2奖励积分扩展是一项功能强大的忠诚度计划,通过构建自动的奖励销售点和支出系统,您可以轻松地将购买者转变为忠实客户。 通过这种方式,商店可以提高销售额,转化率,并一次又一次地吸引顾客。 ***访问销售页面:https://www.mageplaza.com/magento-2-reward-points-extension/ Magento奖励积分是一个合适的模块,可为您创建一个有利的忠诚度计划,该计划可提供magento客户奖励/ magento忠诚度指出并鼓励客户在您的网站上的体验。 使用此模块,您可以绝对使用有用的功能设置一个牢固的起点。 *** Magento奖励积分功能-奖励积分配置-支出积分配置-奖励积分余额管理-积分交易管理-客户积分调整-管理员创建订单时的积分支出-按积分退款-导入/导出积分(热)-积分积分规则插件-积分奖励会员计划插件-积分奖励API ****概述Magento 2积分奖励+是为您创建有利的积分计划的适当扩展,以鼓励客户在您的站点中体验。 使用此标准版,您可以绝对使用有用的功能设置一个牢固的起点。 灵活设置赚取和消费积分的费率管理奖励积分余额,客户奖励积分,并根据需要进行调整-通过积分退款-通过csv文件轻松导入和导出积分1.赚取积分配置Magento奖励积分系统使您的客户在获得积分后可以赚取积分在您的商店下订单。 您可以通过更改“为订单花费的钱”和“赚取积分”,灵活设置客户每次购买可获得积分的条件,例如,“每花费10美元可获得1点”。 magento奖励积分-赚取积分2.消费积分配置使用Magestore积分,在购物车和结帐页面上,客户可以灵活选择要消费的积分。 他们可以向前或向后移动幻灯片,或单击减号或加号图标。 magento奖励积分-消费积分3.奖励积分余额管理使用Magestore Magento 2奖励积分,客户可以跟踪其当前积分余额,该积分余额显示在帐户名称下方的顶部链接中。 Mangeto奖励积分是我们3个忠诚度计划模块之一,该模块还涵盖礼品卡和商店信用magento奖励积分-平衡积分4。积分交易管理管理员可以查看系统的所有积分交易(客户,积分,金额,已使用积分等) )magento奖励积分-积分交易5.客户积分调整在此Magento 2积分模块的后端,管理员可以手动从客户余额中添加或扣除积分。 magento奖励积分-积分调整6.管理员创建订单时的积分消费与客户相似,借助Magento 2客户奖励模块,管理员可以使用积分通过多种方式在后端为他们创建订单:拉动滑块,在空白框中输入数字或勾选“最大化积分折扣”框。 magento奖励积分-积分消费7.按积分退款有趣的是,按积分退款是许多人喜欢的功能。 通过Magestore Magento 2奖励积分功能,管理员可以将客户在商店上花费的积分返还给他们,而不是进行退款,因此他们可以照常用于下一次购物。 它可以节省您的钱并支持您的电子商务管理工作。 magento奖励积分-退款积分8.导入/导出积分Importer Plugin使您可以轻松地以CSV文件格式直接从我们的Magento奖励积分系统导入和导出客户的积分余额。 管理员可以使用CSV文件一口气快速,有效地更新带有数百甚至数千个客户积分余额的奖励积分系统。 这适用于导入新客户的积分余额以及将数据从其他积分系统迁移到您现有的Magento奖励积分。 magento奖励积分-导入积分9.奖励积分规则插件规则插件可帮助您使Magento奖励计划多样化:创建更多规则:商品目录规则和购物车规则。 将某些特定产品设置为仅凭积分购买。 请注意:现在,此插件可用于Magento 1 magento奖励积分-rewardpoints-rule-plugin10。奖励积分忠诚度计划插件忠诚度级别插件是客户对其忠诚度系统最需要选择的插件之一。 使用此插件,您可以:创建和管理具有不同优惠待遇的不同客户组。 允许您的客户根据累积的积分或总销售额(HOT)自动加入组。 请注意:现在此插件可用于Magento 1 magento奖励积分-rewardpoints-loyalty-plugin 11.奖励积分API奖励积分API允许您通过提供调用来处理您的电子商店,这些调用用于处理诸如客户,交易,参考等资源。朋友,行为和转移。 奖励积分客户API; 奖励积分交易API; 奖励积分Referfriends API; 奖励积分转移API; ***查看完整功能列表赚取积分配置设置客户每次购买可获得奖励积分的条件设置具有不同优先级的许多赚钱率设置赚取积分的有效期选择保留客户几天的积分花费积分配置允许客户选择要在购物车和结帐页面
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值