Opencart – PHP Coding (Constants)

This is the first part of what will be many articles on PHP coding as it involves Opencart. I was hoping to share some of my own knowledge on the subject as well as others along the way. This can be for the beginner coder that is just starting out in the world of PHP , or for the more seasoned coder. Some folks don’t really care to know about the inner workings of PHP but for those that are say for example “going to design their own theme” , it’s good to at least have a basic knowledge of PHP. It would definitely help you understand the magic of Opencart and expedite your development as a whole.

PHP Constants

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren’t actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Example:

<?php

// Valid constant names
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR", "something more");

// Invalid constant names
define("2FOO",    "something");

// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something");

Now let’s look at an example of where Constants can be found defined in Opencart. In your Opencart store directory open /config.php after you run the install and you will see quite a few constants. Here is an example:

<?php

// HTTP

define('HTTP_SERVER', '*******************');

define('HTTP_IMAGE', '*******************');

define('HTTP_ADMIN', '********************');



// HTTPS

define('HTTPS_SERVER', '*******************');

define('HTTPS_IMAGE', '********************');



// DIR

define('DIR_APPLICATION', '*******************');

define('DIR_SYSTEM', '*******************');

define('DIR_DATABASE', '*******************');

define('DIR_LANGUAGE', '*******************');

define('DIR_TEMPLATE', '*******************');

define('DIR_CONFIG', '*******************');

define('DIR_IMAGE', '*******************');

define('DIR_CACHE', '*******************');

define('DIR_DOWNLOAD', '*******************');

define('DIR_LOGS', '*******************');



// DB

define('DB_DRIVER', 'mysql');

define('DB_HOSTNAME', 'localhost');

define('DB_USERNAME', '*******************');

define('DB_PASSWORD', '*******************');

define('DB_DATABASE', '*******************');

define('DB_PREFIX', '');

?>

The **************** is hiding my own details for security reasons. Since this config.php file is included at the top of each and every single Opencart page on the front end then you can use the constants at will. Here is an example of how you could use the constant DIR_IMAGE:

		} elseif (!empty($category_info) && is_file(DIR_IMAGE . $category_info['image'])) {

This is taken from category.php

When using a constant you don’t have to use a $ like you would in a variable. The important thing is that the way the constant is spelled matches across the board. Remember that a constant is case sensitive too.

Using CONST

You can also just use

<code><span class="kwd">const</span><span class="pln"> FOO </span><span class="pun">=</span> <span class="str">'BAR'</span><span class="pun">;</span></code>

However, remember that CONST cannot be used to conditionally define constants. It has to be used in the outermost scope.

Looking for quality OpenCart Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , | Posted under OpenCart | Leave a comment

WordPress – Allow Users to Edit Their Comments

How many times have you felt the need to edit a comment you just left on a site? Maybe you want to correct a spelling or grammar error, or maybe you just regret saying something silly. It happens to all of us. Except most sites do not allow users to edit their comments once it is published. If you run an active site with a lot of comments, then you may have considered allowing users to edit their own comments. In this article, we will show you how to allow users to edit their comments in WordPress for a short period of time.
Learn More

Tags: , , , , , , , , , , , | Posted under WordPress | Leave a comment

Getting Multiple Object Fields — FAST

In some previous articles, we discussed a fast way to get individual object fields in MODX Revolution with getValue(), but what if you need more than one field?

In this article, we’ll look at a very fast way to get multiple object fields and place them in a PHP array without retrieving the whole object.

 

MODX logo

 

The Method

This is an example that gets several resource fields from the resource with the ID 12:

$query = $modx->newQuery('modResource');
$query->where(array('id' => '12'));
$query->select(array(
    'ID'        => 'id',
    'Class'     => 'class_key',
    'Context'   => 'context_key',
    'Published' => 'published'
));
$results = array();
if ($query->prepare() && $query->stmt->execute()) {
    $results = $query->stmt->fetchAll(PDO::FETCH_ASSOC);
}

echo print_r($results, true);

 

The code above will display something like this:

Array
(
    [0] => Array
        (
            [ID] => 12
            [Class] => modDocument
            [Context] => web
            [Published] => 1
        )
)

 

Note that the terms on the left side of the select() array are arbitrary “aliases”. You’re free to use the actual field names, but whatever you use will provide the keys for the $results array. That allows you to use them as captions in the output instead of the actual field names, as in the example below. The values on the right must be the actual field names.

 

Things to Remember

In order to use this method, you need to know the actual names of the fields you need. You can find the available fields for each MODX object here.

As we saw in the previous article, the results will be in a nested array, even if there’s only one result. It will be an array where each member is an array of 'fieldname' => 'value' pairs representing one row of the table. If we had used the code below for the where clause, we’d get many results, each nested under the larger array:

$query->where(array(
    'published' => '1',
));

 

You also need to remember that, just like in the previous article, you will be getting the raw field values because the data is not being passed through the xPDO get() method. Date fields will be in the form of Unix timestamps and fields like the modUser object’s extended field and the properties field for resources and elements will be returned as JSON strings. If you are getting a TV values, you’ll also get the raw, un-rendered values, which might be @INHERIT, for example.

 

Walking

Because we created our own array keys in the code above, we can walk through and display the array with nested foreach loops, like this:

foreach ($results as $result) {
    foreach ($result as $key => $value) {
        echo "\n<br/>" . $key . ': ' . $value;
    }
}

The output of that code for each object would look something like this:

<br />ID: 12
<br />Class: modDocument
<br />Context: web
<br />Published: 1

 

This double foreach loop will only work if you can display the raw field values without processing any of them.

 

Using Tpl Chunks

Rather than the double foreach loop shown above (which usually isn’t very practical), you can use a Tpl chunk with placeholder tags to format the data, and still have very fast page-load times. Using our example query above, here’s an example using a simple Tpl Chunk.

 

MyChunk Tpl Chunk

<p>ID: [[+ID]]</p>
<p>Class: [[+Class]]</p>
<p>Context: [[+Context]]</p>
<p>Publisher: [[+Published]]</p>
<p>&nbsp;</p>

 

The PHP Code

$output = '';
foreach ($results as $result) {
    $output .= $modx->getChunk('MyChunk', $result);
}
return $output;

 

At first glance, this looks like the standard way to process results using the Tpl chunk, but it’s not. Notice that the placeholders are not the actual field names — they are the “captions” (more correctly, the “aliases”) from the *left* side of the $query->select()array we used above to get the data. In the standard Tpl chunk usage, we call toArray() on the objects and the actual field names are the “keys” of the resulting array. In this case, we were able to create our own aliases in the select() call.

That said, it’s usually a good idea to use the actual field names (assuming that you know them) for both the select() call and for the placeholders just so that, when entering the placeholders, you don’t have to remember exactly what aliases you used. If you already have the Tpl chunks and are converting to this method, you’ll definitely want to use the actual field names for the aliases — that way the Tpl chunk won’t need to be changed.

 


For more information on how to use MODX to create a web site, see my web site Bob’s Guides, or better yet, buy my book: MODX: The Official Guide.

Looking for quality MODX Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , | Posted under MODX, MODX | Leave a comment