如何从Magento2中的控制器调用模型方法

时间:2015-08-13 03:03:14

标签: controller magento2

我有一个名为List<String> al = new ArrayList<>(Arrays.asList("A", "XYZ", "AXTU")); List<Integer> bl = Arrays.asList(2, 4, 6); List<String> merged = new ArrayList<>(); for (int len : bl) { Iterator<String> iter = al.iterator(); while (iter.hasNext()) { String str = iter.next(); if (str.length() <= len) { merged.add(str); iter.remove(); } } merged.add(String.valueOf(len)); } System.out.println(merged); 的模型,模型有一个函数demo()print&#34; Hello World!&#34;。

如何从名为[A, 2, XYZ, AXTU, 4, 6] 的控制器调用函数demo()?

提前致谢!

2 个答案:

答案 0 :(得分:2)

如果您的模型\Demo\HelloWorld\Model\Customer后面有一个表,您应该使用工厂来实例化它 工厂不需要创建,它将自动生成,但您需要将其注入控制器的构造函数中:

<?php
namespace Demo\HelloWorld\Controller;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $customerFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Demo\HelloWorld\Model\CustomerFactory $customerFactory
    ) {
        $this->customerFactory = $customerFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $customer = $this->customerFactory->create();
        //here you can call load or any other method
        //$customer->load(2);
        //then call your method
        $customer->demo();
    }
}

答案 1 :(得分:1)

只需在控制器的构造函数中注入您的模型,Objectmanager将为您完成所有工作。这应该是这样的:

<?php
namespace Demo\HelloWorld\Controller;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $customerModel;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Demo\HelloWorld\Model\Customer $customerModel
    ) {
        $this->customerModel = $customerModel;
        parent::__construct($context);
    }

    public function execute()
    {
        $this->customerModel->demo();
    }
}