0

I have a task to convert the standalone PHP files to Magento's MVC. These PHP files were created by another developer. The code in the PHP file accesses the database, converts the result into JSONP format and forward it to the frontend developer.

I don't have any knowledge of Magento's MVC. Is this task of conversion similar to the modules in the app/code/core/Mage in the Magento folder?? How can I do this? Is the magento MVC the same as the PHP MVC?

I am including the php file that I need to convert to Magento MVC. So it will be easier for you to understand..

<?php header('content-type: application/json; charset=utf-8');
$link = mysqli_connect("localhost", "db_username", "password", "db_dbname");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$pid = $_REQUEST['prodid'];

/* Select queries return a resultset */

$result = mysqli_query($link, "SELECT round(rating_summary / 20) AS search_rating FROM review_entity_summary where store_id = 1 and entity_pk_value=" . $pid);

// printf("Select returned %d rows.\n" . "<br>\n", mysqli_num_rows($result)) . "<br>\n";
//$string = $_REQUEST['varname'];
    $rows = array();
  /*  while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }*/
//while($r = mysql_fetch_assoc($result)) {
while ($r = mysqli_fetch_assoc($result)) {
    $rows = $r;
//print_r ($rows) . "<br>\n";
}
$json_data = json_encode($rows);
print_r ($json_data);
    /* free result set */
   // mysqli_free_result($result)

mysqli_close($link);
?>

So how can I convert this file to Magento's MVC style?? IS this necessary to convert this file to magento MVC?

Pavan Kumar
  • 1,735
  • 2
  • 28
  • 47
  • 1
    Why have you tagged this with three different versions? Are you using three different versions? Or do you not kow which version you're using? – APC Feb 07 '13 at 05:52
  • What do you mean with "the PHP MVC"? There is no such thing. The answer how to convert the code highly depends on its structure, but yes, writing your own modules for Magento follows the same rules like the core modules. – Fabian Schmengler Feb 07 '13 at 10:20
  • 1
    @PavanKumar: Stop rolling back valid edits! – ThiefMaster Feb 07 '13 at 12:39

2 Answers2

1

I think what they are asking you to do, is to convert code that look like

require_once 'path/to/magento'. "/Mage.php";
umask(0);
Mage::app("default");
....

In to Magento MVC (module)

\app\code\local\MyNamespace

If you're new to OOP, take a look here: http://www.php.net/manual/en/language.namespaces.rationale.php

\app\code\local\MyNamespace\Appname

Name of new custom module - try to keep at least first letter capital, or there WILL BE truble with Magento's understanding

\app\code\local\MyNamespace\Appname\Block

In classic MVC architecture, this represents View part of MVC

\app\code\local\MyNamespace\Appname\controllers

This is fairly easy to understand, if not, have fun: http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller

\app\code\local\MyNamespace\Appname \etc

Contains the most significant part in Magento's MVC architecture - the xml field that will connect all things together

\app\code\local\MyNamespace\Appname\Helper

Intended for files that contain repeatable routines or simple procedural methods

 \app\code\local\MyNamespace\Appname\Model

Same thing as for controller, take a look at the link above

 \app\code\local\MyNamespace\Appname\sql

This was interesting thing to find out what's it for, it's to define custom database tables and process any upgrades to your extension.

 \etc\modules

Contains all Modules included in Magento - here's where it all really begins for our module

see http://inchoo.net/ecommerce/magento/basic-folder-structure-for-new-magento-module/

MagePal Extensions
  • 17,646
  • 2
  • 47
  • 62
  • Thank u sir for explaining as so easier.. I have the php file just for querying the database. For example, the php file contains a simple 'select' query to get the data from database and it converts the result from database and converts to jsonp format. Usually I dont know for what requirement we create the modules in magento?? Is my requirement is similar to create the module in magento? Let me know if you didnt get it?? – Pavan Kumar Feb 07 '13 at 16:56
  • Without see the select query, it hard to say, but you could either use ORM or add the sql query as a method in you model class. Take a look ORM @ http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-5-magento-models-and-orm-basics – MagePal Extensions Feb 07 '13 at 17:17
  • The query is as below: SELECT t1.detail, t2.entity_pk_value, t1.nickname, t1.title, t1.review_id FROM review_detail AS t1 INNER JOIN review AS t2 ON t1.detail_id = t2.review_id WHERE entity_pk_value =16. So is my requirement is similar to creating a module?? – Pavan Kumar Feb 08 '13 at 05:21
  • Sir, what ever you have expected is right. They asked me to convert into what ever you have explained, But I havent get correct methods and procedures that we need to use in the block and controllers and other folders. can you give me some sample code link for this... – Pavan Kumar Feb 15 '13 at 07:46
  • Depending on how complicated you want to get.. you could do this using only a controller, helper and/or model...what I would recommend is start with an example on how to create a custom magento module, then ask more specific question.. Also see http://www.magentogarden.com/blog/working-with-ajax-and-json-in-magento.html – MagePal Extensions Feb 15 '13 at 13:53
0

Interesting question. IMHO, you are in the position I was with regard to Magento some time ago. To write and use mySql queries against the Magento database requires nothing from the MVC model. In our world, I call these voodoo files. I create tools for my staff with very specific purpose and non-published URLs. You can put them anywhere in the file system, just make sure that the directory name and file name do not have any magic meaning within Magento or you might inadvertently disable some function. My sales tax reporting tool is exactly like yours, where you open a connection to the mySql database and make direct, manual queries against it.

RS's answer is a great primer for getting into the MVC. I have started using it for my voodoo tools as well. Making queries the "Magento way" via their controllers can make getting information out of the EAV much easier than trying to put together the info via manual queries because the infrastructure is already coded for you. An example is customer information! I figured out sales tax queries (which was no minor undertaking), but getting a complete name, address, and email was absurd.

I created an export tool which outputs JSON data. I then CURL it from the server at work to store the sales into a mysql database. From there, they get imported into quickbooks. This order export tool is 100% Magento objects like from the example below.

Here is the code I used in my voodoo customer info tool:

// this limits access to the page to this IP address, perhaps your office?
    $remote_host_ip='198.75.43.24';
if( $_SERVER['REMOTE_ADDR'] != $remote_host_ip ){
    $error[ date("Y-m-d_H:i:s") ]="\$_SERVER['REMOTE_ADDR'] is ".$_SERVER['REMOTE_ADDR']." which is not the office ip! $remote_host_ip\n";
}
// from: http://fishpig.co.uk/blog/direct-sql-queries-magento.html
require_once '/home/(your host username)/public_html/app/Mage.php';
// from: http://stackoverflow.com/questions/7145373/magento-fatal-error-call-to-a-member-function-getmodelinstance-on-a-non-obje/7145570#7145570
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(0);
// from: http://www.magentocommerce.com/boards/viewthread/297092/
$_dealers = Mage::getModel('customer/customer')
    ->getCollection()
    ->addFieldToFilter('group_id', array(6,5,3)) 
    //  ->addFieldToFilter('group_id', 6) 
    ;
// print_r($_dealers);
$dealers=Array();
foreach( $_dealers as $id => $obj){
    // $info=$obj->load();
    // print_r($info);
    // from: http://www.42droids.co.uk/magento-get-customer-and-address-details
    $customerAddressId=$obj->getDefaultBilling();
    $address = Mage::getModel('customer/address')->load($customerAddressId);
    $_addr=$address->format();
    $addr.=",".$address->telephone;
    $addr.=",".$obj->email;
    echo "$addr\n"; //var_dump($addr);
}

I do most of my learning by google, trial, and error; so please consider that "my way" is simply one that works for me and probably still isn't the best or easiest way. Also, I still don't completely understand how some of the objects work, hence debug output that's commented out.

My advice would be to not try too hard to make something for the "frontend" facing the customer. Getting pages to display and work correctly in Magento is a miserable experience. If you're able to do sneaky hidden voodoo tools, try to do that. If you're forced to make a module, there are a couple dozen step by step how-to's on the net that can guide you.

Krista K
  • 21,503
  • 3
  • 31
  • 43
  • Sir thank u for helping me regarding this.. but where I have to save these files? Are these to be placed in app/code/locale folder? How can I run these files?? – Pavan Kumar Feb 09 '13 at 06:45
  • 1
    One safe place to save the files is `var/export`. The location is irrelevant. You can process the script by using `ssh` and getting a command line on your host. Or it can run via HTTP accessing the URL in a browser. If using a browser, output a `
    ` near the top and it'll make plain text.
    
    Example, you make `sneaky_customer_list_export.php` and save it in `var/export`, you access it via the url: `http://yourMagenoWebsite.com/var/export/sneaky_customer_list_export.php` It can be access via a web browser or from another PHP script (or any script that can read http streaming) via a SOAP call.
    – Krista K Feb 11 '13 at 04:58
  • Sir thak u so much for giving me replies.. what is the difference in between my code and ur suggested code? The returning RESULTS both are same only na.. If I want to execute my code, I need to call it through the URL and same process for ur code also. So what is the use of converting my standalone php code to magento EAV structure?? – Pavan Kumar Feb 12 '13 at 07:13
  • @PavanKumar my answers should explain it enough, I'm sorry, I'm not sure how to explain what I am saying differently. – Krista K Feb 13 '13 at 00:11