Development Information

May 12, 2012

Database Object – What the Configuration values mean

Filed under: Database Class Information,Tutorials — judda @ 9:37 am

As mentioned in my previous post, there are a few configuration settings that are used, this post will define the meaning of each of them.

Hostname="localhost"
Username="testing"
Password="testing"
Engine="mysql"
Database="testing"
ErrorReporting=2
ErrorLog="logfile.log"
LogQueries="true"
QueryMode=0

Hostname: (normally localhost) the IP address / name of the host that you will be connecting to

Username: the username to connect to the database with

Password: the password to connect to the database with

Engine: the database engine to use

ErrorReporting: The error reporting level(s) that are desired from the database object.  This can be any combination of the following constants (however if used in an INI file you will have to manually set the value).

ERRORS_IGNORE = 0 – Ignore any error messages that come up

ERRORS_ECHO = 1 – Echo any error messages to the screen

ERRORS_EXCEPTION = 2 – Throw an exception whenever there is an issue

ERRORS_LOGFILE = 4 – Write the exception to the log file (located in the ErrorLog configuration setting)

You are able to mix and match any of these levels (except for ERRORS_IGNORE).  For example, in the PHP code you could do the following:

$config->errorReporting=DatabaseConfiguration::ERRORS_ECHO | DatabaseConfiguration::ERRORS_EXCEPTION;

And you would get the errors both echoed out to the screen AND an exception would be thrown.

ErrorLog: If error logging to a log file is enabled, then the error messages will be written here (need to have write access to it).

LogQueries: Whether or not you want a query log stored in memory with the object (useful for helping to determine long running queries and various other query stats)

QueryMode: One of two settings which will define the way that the queries get parsed for parameters.

QUERY_DEFAULT = 0 – Use the new style parameters (i.e. {0:uf})

QUERY_CLASSIC = 1 – Use the classic style parameters (i.e. %uf)

With these values in mind, you are able to set up the object and start querying your database.

Configuring the Database Object

Filed under: Database Class Information,Tutorials — judda @ 9:23 am

The first step to using the database object is the configuration of it.  Essentially at the configuration process is just the hydrating of the DatabaseConfiguration object.  There are four relatively easy ways to do this.

Next post I’ll explain what each of these mean, and what values they should contain.

They are as follows:

1 – Using an INI file

DatabaseConfiguration::fromINIFile($iniFile, $section=NULL)

If you store your configuration settings in a .ini file, you are able to use that to configure the object.  The ini file should look as follows:

; Configuration INI File for Database Configuration
[Database]
Hostname='localhost'
Username='testing'
Password='testing'
Engine='mysql'
Database='testing'
ErrorReporting=2
ErrorLog='logfile.log'
LogQueries='true'
QueryMode=0

With this as your ini file you can then call the static method DatabaseConfiguration::fromINIFile passing it the full file path to this ini file and if there is a section (i.e. the ‘Database’ in the ini file seen above) then provide it that name, and then it will automatically configure the rest for you.

2 – Using an INI string

DatabaseConfiguration::fromINIString($iniString, $section=NULL)

You may already have the body of an ini file in memory, so this way works just like the previous method but instead of reading the contents of the ini file from a flat file, it will just load it from a string.

3 – Using an array

DatabaseConfiguration::fromArray($config)

If you have an array which contains the following key values (keys the same as seen in the above example) then you can set up the object using that.

$array = array (
    'Hostname' => 'localhost'
    , 'Username' => 'testing'
    , 'Password' => 'testing'
    , 'Engine' => 'mysql'
    , 'Database' => 'testing'
    , 'ErrorReporting' => 2
    , 'ErrorLog' => 'logfile.log'
    , 'LogQueries' => 'true'
    , 'QueryMode' => 0
);

4 – Manually Hydrating the object

If none of the previous options work for you, then you are always able to manually create an instance of the DatabaseConfiguration object and populate each of the values by hand.

$config=new DatabaseConfiguration();
$config->hostname = 'localhost';
$config->engine = 'mysql';
$config->database = 'testing';
$config->username = 'testing';
$config->password = 'testing';
$config->errorReporting = DatabaseConfiguration::ERRORS_EXCEPTION;
$config->errorLogFile = 'logfile.log';
$config->maintainQueryLog = true;
$config->queryMode = DatabaseConfiguration::QUERY_DEFAULT;

August 22, 2010

Mini MVC – How to Use – The Base Controller

Filed under: Mini MVC Information,Tutorials — judda @ 1:33 pm

Sorry for the horribly long delay but here is a quick run down on how to extend the BaseController to write your personal controllers.

As mentioned before, the controller acts as the liaison between the model and the view. These are the classes which get looked for and called whenever your site is visited. For example, if your site is http://www.site.com and the URL is http://www.site.com/about, then Mini MVC will automatically look for the controller named ‘AboutController’ in the ‘./app/controllers/’ directory. The class name for each controller should have the name ‘Controller’ at the end, in order to prevent any namespace collisions between the controllers and the models. It also allows you to quickly and easily determine the difference between the two.

For each controller, you can have as many methods as you would like. These methods are also accessible through the web depending on the URL. For example, http://www.site.com/about/contact would call the ‘contact’ function within the ‘about’ controller. If no function name is provided in the URL, then the default function which is called will be used. This is defined in the configuration file (./app/config/config.php) as the __DEFAULTFUNCTION__. The default function which is called in ‘index’.

Please Note: if you don’t want a function to be web-accessible, prefix it with __ and it will be automatically ignored.

When making your own controller, you should always extend the base class (BaseController) because it provides a bit of additional functionality which is not available if you only make it extend the base class. For example, when you are using a model in your controller, you can then use

$this -> __loadModel ( 'ModelName' );

to load the model into memory and then access it directory through the instance of the controller (i.e. $this -> ModelName).

A sample controller will look like this:

<?php
class SampleController extends BaseController // Accessible by the web through http://www.site.com/sample
{
    public function __construct ()
    {
        parent::__construct (); // Always call the parent's constructor to initialize all information
    }
 
    public function index () // Will be called if no function name is provided (i.e. http://www.site.com/sample)
    {
         // In here you will do any of your data manipulation or generation
         // and tell it what views and models to use
         Base::__loadViews ( array (
                 // Define the 3 parts of the view (header, body and footer) - these definitions are not necessary but they are useful
                 Base::VIEW_HEADER => array ( 'header.php' /* The view name(s) to use for the header */ ),
                 Base::VIEW_BODY => array ( 'body.php' /* The view name(s) to use for the body */ ),
                 Base::VIEW_FOOTER => array ( 'footer.php' /* The view name(s) to use for the footer */ )
             ),
                 // Any variables to send in
                 array (
                     // Please Note: All variables MUST have a name associated with them.
                     'key' => 'value', // Variables to be accessible to all views (accessible through $key in the view)
                     Base::VIEW_HEADER => array ( 'Title' => 'Welcome' ) // Variables only accessible to the header view (can be done for the body and footers as well)
             )
         );
    }
 
    // The $username variable will be filled in with the value associated with information after the function name
    public function other ( $username ) // Will be called if no function name is provided (i.e. http://www.site.com/sample/other/judda)
    {
         // i.e. http://www.site.com/sample/other/judda => $username = 'judda'
         // In here you will do any of your data manipulation or generation
         // and tell it what views and models to use
         Base::__loadViews ( array (
                 // Define the 3 parts of the view (header, body and footer) - these definitions are not necessary but they are useful
                 Base::VIEW_HEADER => array ( 'header.php' /* The view name(s) to use for the header */ ),
                 Base::VIEW_BODY => array ( 'body.php' /* The view name(s) to use for the body */ ),
                 Base::VIEW_FOOTER => array ( 'footer.php' /* The view name(s) to use for the footer */ )
             ),
                 // Any variables to send in
                 array (
                     // Please Note: All variables MUST have a name associated with them.
                     'key' => 'value', // Variables to be accessible to all views (accessible through $key in the view)
                     Base::VIEW_HEADER => array ( 'Title' => 'Welcome',
                         'name' => $username ) // Variables only accessible to the header view (can be done for the body and footers as well)
             )
         );
    }
}

That is all I can think about for this topic, please feel free to ask any questions about it so I can expand on this tutorial. :)

July 1, 2010

Mini MVC – How to use – The Configuration File

Filed under: Mini MVC Information,Tutorials — judda @ 11:07 pm

Here I am going to give a quick run down about the the Mini MVC project that I have been working on recently and how to use it.

First, let’s start off with the configuration. As I said in my previous post, it will work right out of the box with no modifications needed. However, sometimes things aren’t always how you want them. In these cases it’s good to know what can easily be changed and what cannot.

In the file: ./app/config/config.php

This is the configuration file which comes with the system by default.

Within this section of the configuration file, there is only one thing that you may need to modify. That is the __SHOWINDEX__ defined value. __SHOWINDEX__ will define whether or not the ‘index.php’ will show up in links which are created using the __INDEXPATH__ defined value. If set to TRUE, then it will be added to the link, otherwise it will not be. This is especially useful if mod_rewrite is not enabled on your server. This will just force the application to send everything through the main page instead of masking the use of the ‘index.php’ page.

/* Break up the current path to contain all information */
$split = preg_split ( '/\//', $_SERVER [ 'SCRIPT_NAME' ], -1, PREG_SPLIT_NO_EMPTY );
 
/* Allow the user of the script to decide if the index should be included in urls */
define ( '__SHOWINDEX__', false );
 
/* Define the base path for the script */
define ( '__BASEPATH__', '/' . $split [ 0 ] . '/' );
 
/* Define the index path for the script depending on previous settings */
define ( '__INDEXPATH__', __BASEPATH__ . ( __SHOWINDEX__ ? 'index.php' : NULL ) );

This following section should not be modified just for ease of use:

/* Define where the system libraries are stored */
define ( '__SYSTEM__', __FULLPATH__ . 'system/' );
define ( '__SYSTEMLIBS__', __SYSTEM__ . 'libraries/' );
define ( '__SYSTEMHELPERS__', __SYSTEM__ . 'helpers/' );
 
/* Define the application path */
define ( '__APPPATH__', __FULLPATH__ . 'app/' );
 
/* Define where the user libraries are stored */
define ( '__USERLIBS__', __APPPATH__ . 'libraries/' );
define ( '__USERHELPERS__', __APPPATH__ . 'helpers/' );
 
/* Define the configuration */
define ( '__CONFIG__', __APPPATH__ . 'config/' );

This spot basically defines everything about where stuff within the application is actually stored. For example, we can see the creation of the links to the system helpers and system libraries paths. If any of these values are changed, the corresponding changes should be made in the ./system/ folders.

Next we move onto the definition of the location of the model, view and controllers directories as well as the configuration directory in case there are any other things which require it.

/* Define the configuration */
define ( '__CONFIG__', __APPPATH__ . 'config/' );
 
/* Define the model / view / controller directories */
define ( '__MODELS__', __APPPATH__ . 'models/' );
define ( '__VIEWS__', __APPPATH__ . 'views/' );
define ( '__CONTROLLERS__', __APPPATH__ . 'controllers/' );

The next key part is the following:

/* Define whether to enable error message logging or not, and where to store the log */
define ( '__LOGERRORS__', true );
define ( '__ERRORLOG__', 'error_log' );
define ( '__DISPLAYERRORS__', true );

This defines the actions which happen when an error occurs. These errors are not the errors which are send by PHP, but ones generated by the Mini MVC script when trying to complete any of your tasks.

The first two definitions: __LOGERRORS__ and __ERRORLOG__ work hand in hand. If __LOGERRORS__ is set to true, then all of the errors which occur will automatically be appended to the file defined in __ERRORLOG__.

The __DISPLAYERRORS__ definition is currently set to true however, this should only be used in development because it displays all of the error messages on the screen after all of the other scripts have been run (after your controller has been called). This will make it so you reveal a bit to much information to the user as well as invalidates any HTML which has been emitted (it emits more HTML after the </html> tag which is not allowed.

The next section:

/* Define the default class and method */
define ( '__DEFAULTCLASS__', 'main' );
define ( '__DEFAULTFUNCTION__', 'index' );

Just defines what the application should be doing if it hasn’t been provided any information about what controller nor the function to use.

In summary:

Constant Result
__SHOWINDEX__ If true, the urls generated through using __INDEXPATH__ will contain ‘index.php’ in them. For example, http://www.yoursite.com/model/controller becomes http://www.yoursite.com/index.php/model/controller
__ERRORLANGUAGE__ Allows you to change the language which the error messages are logged in (currently only English exists)
__LOGERRORS__ If true, whenever Mini MVC detects generates an error, it will append it to the specified data file (__ERRORLOG__)
__DISPLAYERRORS__ If true, all of the error messages generated from Mini MVC will be emitted at the bottom of the page.

Hope this helps to make the configuration file a little more clear. Next step, making controllers.

April 23, 2010

Database Class – Like

Filed under: Database Class Information,Tutorials — judda @ 1:13 pm

It has come to my attention that a few people have been stumbling upon how to use the ‘LIKE’ command with wildcards using this database class.  Because of this, I will provide a brief sample of how to use it.

Normally when someone writes a query which uses ‘LIKE’, it is written as follows:

$query = "SELECT `email` FROM `users` WHERE `username` LIKE '%Tom%'";
 
$res = $db -> query ( $query );

However, because of how this database class currently works, this will cause issues (it looks for the percent sign (%) and then tries to find a parameter type to bind to it).  So instead of doing it this way, you must do the following:

$query = "SELECT `email` FROM `users` WHERE `username` LIKE %s";
 
$res = $db -> query ( $query, '%Tom%' );

This will bind the wildcards along with the actual value into the query and end up doing exactly what you need it to do.

Sorry for the inconvenience.

May 15, 2009

How to connect using the Database Class

Filed under: Tutorials — Tags: — judda @ 7:00 pm

I have received questions about how to connect to your database using the database class.  So here is a quick tutorial on how you can connect to the database using the database class.

Firstly we need to start at the top of the PHP page with the following:

require_once ( “/path/to/database/class/database.php”);

For example, “/path/to/database/class” could be nothing meaning that it is in the same directory as the current file, or it could be something like this “include/”.

This will tell PHP that the information about the database class is found on the corresponding file.  After the database class is ‘require’d into the page, there are two ways that you can create the connection.

Method 1:

In the “database.php” file modify the lines that say:

$db_host = “hostname”; /* Normally ‘localhost’ */
$db_name = “database_name”;
$db_user = “database_user”;
$db_pass = “database_pass”;

To be the information for connecting to your database.

For example, if you connect to your database through “localhost” you would change “hostname” to “localhost” as well as for all of the other variables ($db_name, $db_user, $db_pass).

After the login information is all set up for the database class, all you will have to do in the original script is add the following:

$db = new Database (); //Change $db with any variable name you would like your database connection to have

Method 2:

This method is a bit easier and will allow you to use any updated versions of the database class without actually having to remember to change the login credentials in the database.php file.  All you have to do is the following:

$db = new Database ( array ( “host” => “hostname”, “name” => “database_name”, “user” => “database_user”, “pass” => “database_pass” ) );

Where you fill in each of the credentials as they correspond to the values.  For example, if you connect to your database through “localhost” you would change “host” to “localhost” as well as for all of the other values (name, user, pass).

After doing this you should be connected to the database and able to run your queries.

Next Tutorial on how to run queries.

May 5, 2009

Database Class

Filed under: Database Class Information,Tutorials — Tags: — judda @ 10:30 am

I noticed that there are not many good database classes that people implement nowadays in PHP that help prevent against SQL Injection and allow for the validation of the data as well.  So I decided to make one which is based off of ‘printf’ from various languages (i.e. C).

This class originally started as a wrapper class for the ‘mysql_’ set of functions in PHP (version 1) but then was changed to a wrapper class for the PDO object.

Why not just use the PDO/PDOStatement object directly?  It requires you to do extra leg work to ensure that all data is bound properly as well as the validation for the different data types is fairly simple.

In this class, the way that you write the SQL queries will change slightly in order to add a potential layer of security.  Instead of entering the values you want to add into the query directly, you will swap the value out with one of the variable constants (i.e. %s, %d, etc.) based on the type of informaton that you would like to store.

Your queries will start looking like this:

SELECT * FROM `table_name` WHERE `id` = %d

In order to run the query then (after an instance of the database class has already been created) all that is needed is the following (this example assumes that the Database object has been created and is stored in a variable called ‘db’):

$idNumber = 2;

$results = $db -> query ( “SELECT * FROM `table_name` WHERE `id` = %u”, $idNumber );

If the ‘idNumber’ variable fails to validate against the regular expression for the unsigned integer then the query function will return NULL and if verbose mode is turned on then an error message will be displayed on your page saying that the value failed to validate.  Otherwise, the query function will return the PDOStatement that has been executed.  Which then you can use any of the other functions built into the class to actually retrieve the information that is in the records.

Each of the parameters (i.e. %s, %d, etc.) are changed with a parameter that will be bound to the query at a later time during the execution of the query function.  It’s this binding of the parameters to the query, rather than adding them directly in that adds the layer of security.

Powered by WordPress