how to instantiate a model in magento

2019-08-30 08:39发布

问题:

I am new to Magento and currently am following this tutorial.

The tutorial seems very clear and helpful although I cant get the

include(Alan/Storm/Model/Blogpost.php) [function.include]: failed to open stream: No such file or directory

error to display, my errors are switched on. Obviously this wouldn't be a problem if I could display the model name as the tutorial states in the next step, but im missing something and need some guidance on my code please.

Alan/Storm/etc/config.xml

<config>
<modules>
    <Alan_Storm>
        <version>0.1.0</version>
    </Alan_Storm>
</modules>

<models>        
    <storm>
        <class>Alan_Storm_Model</class>            
        <resourceModel>storm_mysql4</resourceModel>
    </storm>
</models>

<frontend>
    <routers>
        <storm>
            <use>standard</use>
            <args>
                <module>Alan_Storm</module>
                <frontName>storm</frontName>
            </args>
        </storm>
    </routers>
</frontend>

Alan/Storm/controller/indexController.php

class Alan_Storm_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction() {
    echo 'This is the Alan Storm Module';
}

public function testModelAction() {
    $blogpost = Mage::getModel('storm/blogpost');
    echo get_class($blogpost);
}
}

I have tried leaving the Alan/Storm/Model folder empty but I just got a blank screen when I visited http://magentotest.local/storm/Index/testModel. I have also tried to add Blogpost.php to the Model folder, but that has not helped.

What am I doing wrong?

EDIT!

I have changed

    public function testModelAction() {
    $blogpost = Mage::getModel('storm/blogpost');
    echo get_class($blogpost);
}

to

public function testModelAction() {
    $blogpost = Mage::getModel('storm/blogpost');
    echo get_class($blogposts);
}

Why does this work? I havn't created a variable called $blogposts prior to using the get_class funciton. It is worth noting that my table within the databse is called blogposts, but I dont see how that would make this adjustment in the script work.

EDIT 2

The new method only displays the name of the controller im working in, not the model/blogpost.php, which is what I thought i was asking for

回答1:

Based on the code sample you provided, you have your <models/> tag in the wrong spot.

You've placed it directly under the <config/> node.

<!-- this is wrong -->
<config>
    <models>     
        <!-- ... -->
    </models>
</config>

It should be under the <global/> node

<config>
    <global>        
        <models>
            <!-- ... -->
        </models>
    </global>
</config>

You may have been tripped up by the code sample, which only shows a partial fragment, and not the entire document tree. Notice the top level node is <global/>

Those code samples could be clearer — I was still getting my tutorial writing legs under me back then.



标签: magento