Prog how-to

general programming

Archive for the ‘php’ Category

PHP Calendar Control

Saturday, May 9th, 2009

Short description

Here is a fully customizable calendar control for your PHP applications. It is entirely written in php and can be easily adapted to your needs. Also it is free. The download links are displayed below:

Download

Download the component only here. This package contains only the classes afferent to the control.

I strongly recommend you download all the test classes (which include the Calendar classes as well), for a “live” use example. The full test package can be downloaded here. Here is the test link to see the control at work. One thing: prototype.js contained in the archive is the prototype framework used for Ajax and it is just a bundled reference, not an actual part of the project.

How it works

The calendar shows a full month. The header contains the current month and the year, plus two links to be used to switch to the previous / next month.

A date considered “selected” is rendered with a different CSS.

There is no formatting data in the calendar other than the generated CSS classes attached to various html tags. The programmer and the designer are the ones that will decide how to put together the needed CSS in order to make the control blend in the website.

Here is how the calendar looks like (it was taken from the test that can be found here).

There are links in the header on the left and right arrow shown and on each date. Each hyperlink triggers a Javascript function – there are default names for these functions. These names can be also changed

The control is not rendered in Javascript. Reasons: it requires a lot of javascript, plus if you need to display information other than just the days (and we need to display this additional information) then you need a roundtrip anyway.

Then what would be a good approach to change the calendar state (rendering):

  • Wrap the calendar in another control let’s say<div class=’calendar’ id=’item1′>
  • If the page is entirely rendered, just echo the component html where you want the calendar displayed
  • If you want to change the calendar in place, then
    1. The Javascript functions triggered by the calendar shall send an Ajax request
    2. The callback function receives a json containing among other things the html associated with the calendar new state
    3. Replace the current calendar with the new one like that: document.getElementById(’item1′).innerHTML=retrieved_html
  • Please try the test – it has all the Ajax stuff. It sounds tough, but actually it is extremely simple to implement!!!!

Features

Here is a list of features:

  • Shows the current month, year
  • Uses only CSS class names for rendering control. The programmer has to fully provide his own CSS definition that will make the calendar blend in his website
  • There is a “selected date” that will be rendered using a different CSS class
  • Besides the days in the calendar, you can show some additional data defined in a hash array before the rendering.
  • The control has some links that trigger Javascript functions. The functions will be implemented by the programmer usually in order to whatever is needed on the server side according to the business requirements and prepare the calendar control for a new state.

Structure

The calendar is shipped in two PHP clases, a value object class with all the settings called CalendarData and the Calendar class with all the rendering, etc.

In a nutshell, here is how to use the control:

  • Create an instance of CalendarData
  • Fill out the needed attributes
  • Create an instance of Calendar (passing the reference to the already created CalendarData object)
  • Retrieve the control html using the accessor getHtml() from the calendar object

Depending where you are in your application, you can do the following:

  • Echo the html in the appropriate place in order to have it rendered in the page
  • If you are in the middle of an Ajax request processing, put the html in the object that will be converted later to json so that you will have the information in the request callback
public $year; The year for current displayed month
public $month; The month for the current displayed month. The year and the month are mandatory for the control to be displayed. The rest of the values are not mandatory and default values are provided by the CalendarData constructor
public $selmonth; The month for the selected date
public $selyear; The year for the selected date
public $selday; The day of month associated with the selected date. If the selected date is defined and belongs to the month currently displayed, then the selected date will be displayed using the css class “selected”. Appropriately modifying the CSS file you can make this date show different than the others.
public $values; The values attached to the current calendar. If they are within the currently displayed month and $showValues is true, then the values will be displayed besides the calendar days. The following things must be taken into account:
The key format is yyyy-mm-dd, without trailing zeros for mm and dd (use 2009-2-2 instead of 2009-02-02)
The value associated with the key must be any string. That string will be retrieved if the values are to be displayed and placed as we mentioned before, besides the associated day.
public $showValues; True to show the values associated with the days, false otherwise
public $showDefault; True to show the default values for the days that don’t have values already defined in the $values array. Attention – in order for the default values to be displayed you need to have $showValues true as well.
public $left; In case the values are displayed, then this string is placed between the day and the value. The defaut value is &nbsp;( this will open a braket and will ensure it is on the same line as the day of month
public $right; Please see the explanation above for $left. $right has a similar meaning, except will be added immediately after the value.
public $defaultValue; If showDefault is true, then the days that don’t have specific values defined in the $values array will have this value displayed. By default is 0.
public $functionSelect; The name of the Javascript function that is triggered when any calendar date is clicked. The default name is select, however you might want to define your own.
public $functionPrevious; The name of the Javascript function that is triggered when the “previous” link on the control header is clicked.
public $functionNext; The name of the Javascript function that is triggered when the “next” link on the control header is clicked.

Formatting

The control only generates classes attached to some of the table rows and all the table cells. It is programmer responsibility to tweak the css file in order to obtain the desired result. For example, the formatting obtained for our example that can be seen here, was obtained solely by appropriately adjusting the CSS file.

The classes generated by the control rendering functionality are the following:

  • weekday – class attached to the td html tags that wrap around week days.
  • weekend – class attached to the td html tags that wrap around week end days
  • selected – class attached to the td html tag that corresponds to the selected day

If you need to have two calendars on the same page and render them differently, please wrap them in two div tags with different class names (div.calendar1 and div.calendar2) and provide the formatting info in your css file accordingly. Also, worth mentioning that the header lines are wrapped in a thead tag while the other ones are wrapped in a tbody. This will also help with organizing the formatting styles in the css file.

Some Images

Here are some images for the calendar control, in various configurations:
Without any values displayed

With both the values and the default values displayed

With the “width” style associated with the cells removed – so that will occupy minimum space and will look more like the calendars you saw already.

Some Code

Setting Calendar Data

function getData(){
	$dt = new CalendarData();

	// setup some information
	$dt->month = 3;
	$dt->year = 2009;
	$dt->values = array();

	$dt->selday = 12;
	$dt->selmonth = 3;
	$dt->selyear = 2009;

	$dt->values['2009-3-2'] = "4";
	$dt->values['2009-3-5'] = "2.5";
	$dt->values['2009-3-12'] = "1";

	$dt->showValues = true;
	$dt->showDefault = false;

	return $dt;
}

Rendering the Calendar

$dt = getData(); // get the calendar data

$showValues = getToggle($dt->showValues);
$showDefault = getToggle($dt->showDefault);

$cal = new Calendar($dt);

$html = $cal->getHtml();

And then somewhere in your html page:

<?php echo $html; ?>

Configure Apache, PHP and MySQL

Tuesday, April 28th, 2009

This is just another tutorial of how to configure a development machine for Apache, PHP and MySQL

There are packages bundling the three technologies (install the package and everything is there ready to go). They are good for start. However a serious developer should install the latest production bundles from scratch. Couple or reasons:

  • Have complete control of the process
  • Use the versions that you have or intend to have on the production machine
  • Learn how to configure everything. As a programmer, you eventually need to know that.

We are going to present the simplest approach to have all the three packages installed on your machine and have you up and running in the shortest time possible.

We assume you got a machine running Windows XP or 2000 or Vista, and you don’t have any of the required packages installed (if you tried to install them and it did not work, please start fresh).

Please install the packages in the order mentioned below. The reason: for example if you install PHP after you install Apache, then the PHP installation script will automatically integrate with Apache, saving you some time.

Please do not install in the default Windows Program Files folder. Instead, do it in a folder with a short name, directly under the root folder. We installed everything under a folder called c:\devweb

Install Apache

We recommend the use of a Windows msi installation kit. Please follow the installation steps:

  • Proceed to http://www.apache.org/
  • Follow the link “http server
  • Then select “download from a mirror
  • Download the installation kit for Apache 2.2 without Crypto. You don’t need SSL for a development machine at least not for this example
  • At the time of this writing, the file name we downloaded is: apache_2.2.11-win32-x86-no_ssl.msi

Now run the installation kit. Choose the installation folder under the c:\devweb as mentioned above. We chose: c:\devweb\apache2.2.11\

Install PHP

There are Windows installation kits .msi available for PHP as well. That means that the PHP installation is as simple as the one we just did for Apache http server.

Please follow the installation steps as follows:

  • Proceed to http://www.php.net/
  • Select the link under Stable Releases that points to the latest PHP version ready for production
  • Download and launch the installation kit
  • Select the folder where PHP will be installed; we chose C:\devweb\php\
  • When asked for which web server you require installation, please carefully select the web server that that will be used – as per the previous paragraph, we chose Apache 2.2
  • When asked, select the Apache subfolder where httpd.conf resides – in our case, c:\devweb\apache2.2.11\conf. The PHP installation kit will appropriately modify the Apache configuration file to point to the newly installed version
  • Select the extensions that are to be installed during the current process. Please consider that in this case less is more, and only select what you need. We selected only mysql and mysqli. If you need other extensions in the future, just run the PHP installation script again and add the required extensions (the current installation settings will not be affected)

The installation will then be completed. You are now ready to test it. Before doing so, please have a look at the file httpd.conf in the Apache configuration folder to see what are the changes operated during PHP installation. You will see the following lines added at the end:

#BEGIN PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
PHPIniDir "C:/devweb/php/"
LoadModule php5_module "C:/devweb/php/php5apache2_2.dll"
#END PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL

  • Restart the Apache server using the Apache monitor (see the icon in the tray) or directly restart the corresponding Windows service using the management console

  • Rename the file index.html at the location c:\devweb\apache2.2.11\htdocs to index.php and open it for editing
  • Delete all the existent html and insert the following:
<html>
<head>
<title>Test functionality php</title>
</head>
<body>
<?php
  phpinfo();
?>
</body>
</html>
  • Access the index.php at the url http://localhost/index.php. You should show a lengthy table that contains all the PHP configuration information.
  • Please search for the extension names you mentioned at the PHP installation (we mentioned mysql and mysqli) and double check they are there.

At this moment you are done, and (almost) ready to start the development activity on your computer.

Install MySQL

We want a similar easy installation process for MySQL as well. Follow the steps:

  • Proceed to the address http://www.mysql.org
  • Click on “downloads”
  • Under the title MySQL Community Server, click on the “Download” button
  • Proceed with all the needed steps until you are in position to download the intallation kit. Under the Windows binaries, there are many options, please choose the msi insallation kit. At the time of this writing, the file we downloaded is mysql-5.1.34-win32.msi

Now you can proceed with the installation. There are many steps to follow, please run the installation kit and consider the following:

  • Don’t use “default configuration” or “default installation” as you will have to choose some of the settings different than the default ones
  • Install the MySQL under the same top folder as PHP and Apache. We installed ours in C:\devweb\mysql5.1
  • Choose it to run as a service. It is extremely convenient.
  • Choose a root password different than empty one (we chose the word “password”).
  • Just to be on the safe side, after the MySQL installation is done, please restart the Apache web server

Now we are in position to test the end to end installation. We already confirmed that Apache works nicely with our PHP installation, now we have to test that MySQL can be accessed from our PHP scripts

Edit again the file index.php under the folder c:\devweb\apache2.2.11\htdocs (the Apache default document root) and paste the script below. The script connects to the database using the root account you just created and lists the existent databases. Most likely this is the only time you will ever use this sql from a PHP page, however right now it will do the job by showing us we can access the database server from our PHP script.

<?php
	// try to test the database
	// access from the current
	// machine - the program should
	// appropriately list the databases
	// that are currently available on
	// the current machine db server

	$sql = "show databases";
	$connection =
		mysqli_connect("localhost", "root", "password");

	$statement = $connection->prepare($sql);
	$statement->bind_result($val);
	$statement->execute();

	$items = array();
	while($statement->fetch()){
		$items[] = $val;
	}

	$html = "";
	$index = 0;
	foreach($items as $current){
		$index ++;
		$html .= "value at index:
			{$index} is:
			<strong>{$current}</strong> <br/>";
	}
?>
<html>
<head>
	<title>Test database access</title>
</head>
<body>
	<?php echo $html; ?>
</body>
</html>

And here is the result, when accessing the page at url http://localhost/index.php :

Now we are 100% done and ready to start the development. You have to update Apache configuration to have an alias for each project you work at, so that you will be able to work a couple of projects at a time without having to restart Apache every time, however this is just a detail, your main development environment is ready.