views:

14211

answers:

12

Can someone show me how to accomplish the following in Magento:

  • Display a hello world message using a controller/view/model approach, so if i went to http://mysite.com/myController

It would show the string 'hello world'. Being able to show this string within the template of my website (e.g the header, footer, etc) will be a bonus.

  • How to write add a method to this controller (or a new controller if necessary), which interacts with a model, and performs this query:

    Select * FROM articles where id='10'

and returns the row (containing the columns id, title, content) to the controller. And then use the controller to include a view, which would display this row. So going to:

http://site.com/myController/show_row (or something similar)

would display the row within a view. (No need to be fancy, just a echo $row->id; or something similar would work.

Any other info about Magento's code structure will also be very helpful.

Bounty of 300 points will be awarded to the person with the best answer

Edit: Over 3k views and only 1 upvote! If this question is helpful to you, please don't forget to upvote :)

A: 

AFAIK Magento is written in Zend Framework, so I would go read ZF's manual on these topics.

This should be enough - if not - try searching magentoo code manual, as ZF isn't a complete framework - you have to build one from ZF.

dr_bonzo
Magento doesn't have a code manual
Click Upvote
+1  A: 

There is a Magento Wiki that perhaps has answers to some of your questions.

schnaader
+8  A: 

I've been wrestling with Magento for the last month or so and I'm still trying to figure it out. So this is a case of the blind leading the blind. There's little in the way of documentation and the forum/wiki is chaotic at best. Not only that, but there are several solutions that are either outdated or far from optimal. I'm not sure if you have a project or just trying to figure it out, but it's probably easier if you started with modifying existing functionality as opposed to creating something completely new. For that I'd definately go with the "Recommended articles for developers" in the wiki. The new payment method one was a real eye-opener.

For debugging I'd definitely recommend using FirePHP and looking at your HTML source when something goes wrong. The ole echo debug method doesn't really work all that well.

The general architecture is so mind-numbingly complex, that even if I completely understood it, I'd need to write a book to cover it. The best I can do is give you advice I wish someone had given me when I first started...

Stay away from core files. Don't modify them, instead write your own module and override what you need.

Magento uses config files consisting of XML to decide what it needs to do. In order to get it to run your own stuff as opposed to core functionality you need the correct xml. Unfortunately there is no guide on how to build you XML; you need to look at examples and do some serious testing. To complicate things the content of these files is largely case-sensitive. However if you master these you can override any part of the basic functionality which makes for a very powerful system.

Magento uses methods like Mage::getModel('mymodel'), Mage::getSingleton('mysingleton'), Mage::helper('myhelper') to return objects of certain classes. It finds these by default in its core namespace. If you want it to use your own, you need to override these in your config.xml file.

The name of your classes must correspond to the folder they're in.

A lot of the objects in Magento ultimately extend something called a Varien_Object. This is a general purpose class (kind of like a swiss army knife) and its purpose in life is to allow you to define your own methods/variables on the fly. For example you'll see it used as a glorified array to pass data from one method to another.

During development make sure you caching is disabled. It'll make magento excruciatingly slow, but it'll save you a lot of head trauma (from banging it on your desk).

You'll see $this being used a lot. It means a different class depending on what file you see it. get_class($this) is your friend, especially in conjunction with FirePHP.

Jot things down on paper. A lot. There are countless little factoids that you're gonna need 1-2 days after you encounter them.

Magento loves OO. Don't be surprised if tracing a method takes you through 5-10 different classes.

Read the designer's guide here. It's meant mostly for graphics designers, but you need it to understand where and why the output from your module will end up. For that don't forget to turn on "Template path hints" in the developer section of the admin panel.

There's more, but I'll stop here before this turns into a dissertation.

Manos Dilaverakis
Please post more if you can, all info is very helpful :)
Click Upvote
Misa, you should probably register here on Stackoverflow, if you lost your cookie all your rep would be gone ;)
Click Upvote
+76  A: 

First and foremost, I highly recommend you buy the PDF/E-Book from PHP Architect. It's $20, but is the only straight forward "Here's how Magento works" resource I've been able to find. I've also started writing Magento tutorials at my own website.

Second, if you have a choice, and aren't an experienced programmer/don't have access to an experienced programmer (ideally in PHP AND Java), pick another cart. Magento is well engineered, but it was engineered to be a shopping cart solution that other programmers can build modules on top of. It was not engineered to be easily understood by people who are smart, but aren't programmers.

Third, Magento MVC is very different from the Rails/Django/Code Igniter/Cake/etc MVC model that's popular with PHP developers these days. I think it's based on the Zend model, and the whole thing is very Java OOP-like. There's two controllers you need to be concerned about. The module/frontName controller, and then the MVC controller.

Fourth, the Magento application itself is built using the same module system you'll be using, so poking around the core code is a useful learning tactic. Also, a lot of what you'll be doing with Magento is overriding existing classes. What I'm covering here is creating new functionality, not overriding. Keep this in mind when you're looking at the code samples out there.

I'm going to start with your first question, showing you how to setup a controller/router to respond to a specific URL. This will be a small novel. I might have time later for the model/template related topics, but for now, I don't. I will, however, briefly speak to your SQL question.

Magento uses a EAV database architecture. Whenever possible, try to use the model objects the system provides to get the information you need. I know it's all there in the SQL tables, but it's best not to think of grabbing data using raw SQL queries, or you'll go mad.

Final disclaimer. I've been using Magento for about two or three weeks, so caveat emptor. This is an exercise to get this straight in my head as much as it is to help StackOverflow.

Create a Module

All additions and customizations to Magento are done through modules. So, the first thing you'll need to do is create a new module. Create an XML file in app/modules named as follows

cd /path/to/store/app
touch etc/modules/MyCompanyName_HelloWorld.xml 

<?xml version="1.0"?>
<config>
  <modules>
  <MyCompanyName_HelloWorld>
   <active>true</active>
   <codePool>local</codePool>
  <MyCompanyName_HelloWorld>
  </modules>
</config>

MyCompanyName is a unique namespace for your modifications, it doesn't have to be your company's name, but that the recommended convention my magento. HelloWorld is the name of your module.

Clear the Application Cache

Now that the module file is in place, we'll need to let magento know about it (and check our work). In the admin application

  1. Go to System->Cache Management
  2. Select Refresh from the All Cache menu
  3. Click Save Cache settings

Now, we make sure that magento knows about the module

  1. Go to System->Configuration
  2. Click Advanced
  3. In the "Disable modules output" setting box, look for your new module named "MyCompanyName_HelloWorld"

If you can live with the performance slow down, you might want to turn off the application cache while developing/learning. Nothing is more frustrating then forgetting the clear out the cache and wondering why your changes aren't showing up.

Setup the Directory Structure

Next, we'll need to setup a directory structure for the module. You won't need all these directories, but there's no harm in setting them all up now.

mkdir -p app/code/local/MyCompanyName/HelloWorld
mkdir -p app/code/local/MyCompanyName/HelloWorld/Block
mkdir -p app/code/local/MyCompanyName/HelloWorld/controllers
mkdir -p app/code/local/MyCompanyName/HelloWorld/Model
mkdir -p app/code/local/MyCompanyName/HelloWorld/Helper
mkdir -p app/code/local/MyCompanyName/HelloWorld/etc
mkdir -p app/code/local/MyCompanyName/HelloWorld/sql

And add a config file

touch app/code/local/MyCompanyName/HelloWorld/etc/config.xml

and inside the config file, add the following, which is essentially a "blank" config.

<?xml version="1.0"?>
<config> 
 <modules>
  <mycompanyname_helloworld>
   <version>
    0.1.0
   </version>
  </mycompanyname_helloworld>
 </modules>
</config>

Oversimplifying things, this config file will let you tell Magento what code you want to run.

Setting up the Router

Next, we need to setup the module's routers. This will let the system know that we're handling any urls in the form of

http://example.com/magento/index.php/helloworld

So, in your config file, add the following section.

<config>
<!-- ... -->
 <frontend>
  <routers>
   <!-- the <helloworld> tagname appears to be arbitrary, but by 
   convention is should match the frontName tag below-->
   <helloworld> 
    <use>standard</use>
    <args>
     <module>MyCompanyName_HelloWorld</module>
     <frontName>helloworld</frontName>
    </args>
   </helloworld>
  </routers>
 </frontend>
<!-- ... -->  
</config>

What you're saying here is "any url with the frontName of helloworld ...

http://example.com/magento/index.php/helloworld

should use the frontName controller MyCompanyName_HelloWorld".

So, with the above config in place, when you load the helloworld page above, you'll get a 404 page. That's because we haven't created a file for our controller. Let's do that now.

touch app/code/local/MyCompanyName/HelloWorld/controllers/IndexController.php

Now try loading the page. Progress! Instead of a 404, you'll get a PHP/Magento Exception

Controller file was loaded but class does not exist

So, open the file we just created, and paste in the following code. The name of the class needs to be based on the name you provided in your router.

class MyCompanyName_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action{
 public function indexAction(){
  echo "We're echoing just to show that this is what's called, normally you'd have some kind of redirect going on here";
 }
}

What we've just setup is the module/frontName controller. This is NOT the MVC controller. Try the following URL, and you'll get a 404, even if you had a fooAction method in MyCompanyName_HelloWorld_IndexController

http://example.com/magento/index.php/helloworld/foo

So, to setup the MVC controller, create a new file, and enter the following code (Yes, this also extends the Mage_Core_Controller_Front_Action controller, even though it's not a Front Action. Yes, this is confusing, but I think it's how things are done)

touch app/code/local/MyCompanyName/HelloWorld/controllers/FooController.php
class MyCompanyName_HelloWorld_FooController extends Mage_Core_Controller_Front_Action{
 public function indexAction(){
  echo 'Foo Index Action';
 }

 public function addAction(){
  echo 'Foo add Action';
 }

 public function deleteAction(){
  echo 'Foo delete Action';
 }  
}

Yo should now be able to hit the following URLs and see the results of your echo statments

http://example.com/magento/index.php/helloworld/foo
http://example.com/magento/index.php/helloworld/foo/add
http://example.com/magento/index.php/helloworld/foo/delete

So, that should give you a basic idea on how Magento dispatches to a controller. From here I'd recommended poking at the existing Magento controller classes to see how models and the template/layout system should be used.

Alan Storm
Thanks, this is very helpful. Please consider adding some info about using model/database and views so your answer can be complete
Click Upvote
Note to self: Less reading the magento forums, more asking in stackoverflow.
Manos Dilaverakis
I highly recommend the book he linked to as well, i got it today and reading through it now. Its very useful
Click Upvote
Excellent answer, thank you.
John McCollum
wish i could vote you up twice ... thanks!
Rick J
make sure that the app/code/local/MyCompanyName/HelloWorld/etc/config.xml has the same case as the xml located in etc/modules (MyCompanyName_HelloWorld NOT mycompanyname_helloworld) otherwise there will be to entries in the backend!
Moak
+1  A: 

thanks for your detailed explanation. It is really helpful for a newbie.....thanks again

+1  A: 

It's a while since Alan's post, but he has answered this one well. I spent a while working out controllers myself. There are some comments relating to the overriding of existing controllers in the Magento source code app/code/core/Mage/Core/Controller/Varien/Action.php

The Magento source code is very clean and well written, but not very well commented. I highly recommend using Nusphere PhpEd, as it is possible to trace through the code, set breakpoints and examine objects, variables, arrays, etc. to find out what the code is doing. I have PhpEd incredibly useful and signficantly better than FirePHP, but it does cost a few $$$'s. Having said that, I wouldn't be without it.

Make sure you use PhpEd 5.6 build 5641 (the latest as of today) or newer, as the original 5.6 had some bugs that caused some infuriating problems with debugging.

I suggest you get the book alan has recommended in his post, "Php architecture guide for Magento". Its really helpful and explains how the code works, even walks you through the process.
Click Upvote
A: 

(I can't comment on Alan's answer yet, hence a separate answer)

The link to the php|architect's "Guide to Programming with Magento" book is broken. It should now be: http://www.phparch.com/books/isbn/9780973862171

philfreo
I edited it for you
Click Upvote
+3  A: 

I've got just small comment on Alan's perfect answer: "What we've just setup is the module/frontName controller. This is NOT the MVC controller." It is exactly same type of controller as FooController is. In ZF index action in IndexController is called by default, so requesting http://example.com/magento/index.php/helloworld/ will call IndexController::indexAction() in helloworld module. Thus calling .../helloworld/foo will try to find FooController in helloworld module and call indexAction() on it. To trigger IndexController::fooAction() you need to request: .../helloworld/index/foo.

Matus Zeman
A: 

I have successfully created helloworld module.I would like to insert some values like first name last name etc. in to database.Please help me.I am waiting for your valuable reply.

A: 

Remember to add:

<?php

At the top of your controllers when entering in that example.

dimensia
A: 

Excelent..this tutorial gets you trough very nicely, thanks Alan, only to keep in mind adding php initials to Indexcontroller.php , and also disabling cache on magento's backend, not just flushing the cache.

Rafael Ortiz
+1  A: 

Elaborating just a little more on Matus's point:

example.com/magento/index.php/helloworld

is transparently pointing to

example.com/magento/index.php/helloworld/index/index

so basically you have the following URI structure for modules

example.com/magento/index.php/:module/:controller/:action/:param1[/:paramN ...]