Archive

Archive for August, 2008

Script Timing in PHP

August 4th, 2008
Comments Off

Knowing how long something takes to process is very important. However, hand-rolling a timing solution every time you need one can be frustrating. This little class is a very lightweight solution that allows you to to simply start a timer, then capture elapsed time at various points in your program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
 
class Script_Timer
{
    /**
     * Start timer
     *
     * @return BOOLEAN
    */

    public static function start()
    {
        $success = false;
        try
        {
            if(!self::started())
            {
                define('TIMER_START_TIME', microtime());
            }

            $success = true;
        }
        catch(Exception $e)
        {
            //
        }

        return $success;
    }

    /**
     * Check if timer is started
     *
     * @return  BOOLEAN status of timer
     */

    public static function started()
    {
        $started = false;

        if(defined('TIMER_START_TIME'))
        {
            $started = true;
        }

        return $started;
    }

    /**
     * Get timestamp of start time
     *
     * @return STRING   microtime of time start
     */

    public static function get_Start()
    {
        $start_time = null;

        if(self::started())
        {
            $start_time = TIMER_START_TIME;
        }

        return $start_time;
    }

    /**
     * Get number of seconds since script start
     *
     * @param INTEGER   $decimals   number of decimals to capture
     *
     * @return NUMBER   seconds since script start
    */

    public static function get($decimals=2)
    {
        // format start time
        $start_time = explode(' ', TIMER_START_TIME);
        $start_time = $start_time[1] + $start_time[0];
        // get and format end time
        $end_time = explode(' ', microtime());
        $end_time = $end_time[1] + $end_time[0];

        return number_format($end_time - $start_time, $decimals);
    }

    /**
     * Get number of seconds from given count
     *
     * @param NUMBER    $prev_seconds   number of seconds from a previous get() value
     * @param INTEGER   $decimals       number of decimals to capture
     *
     * @return NUMBER   seconds since script start
     */

    public static function diff($prev_seconds, $decimals=2)
    {
        $current_time = self::get(4);

        $diff_seconds = $current_time - $prev_seconds;

        return number_format($diff_seconds, $decimals);
    }
}

The example below shows how the class is used statically so that the scope of an instantiated timer object doesn’t become a problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// start timer  Script_Timer::start();

// do some processing.....  

// Then when you are ready to get current time since start, run:

$new_time_1 = Script_Timer::get();

// do some processing.....

$new_time_2 = Script_Timer::get();

// You can also get the difference from another time until current:

// do some processing.....

$time_diff = Script::diff($new_time_2);

You can even set the timed values to an arrar or session, so that you can keep them together and run evalutions and comparisons on them later.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// start timer
Script_Timer::start();

$_SESSION['timer'] = array();

// initiate first time capture

$_SESSION['timer']['start'] = Script_Timer::get();

// do some processing.....

$_SESSION['timer']['point_a'] = Script_Timer::get();   

// do some processing.....

$_SESSION['timer']['point_b'] = Script_Timer::get();

// do some processing.....

$_SESSION['timer']['point_c'] = Script_Timer::get();

$point_c_processing_time = $_SESSION['timer']['point_c'] - $_SESSION['timer']['point_b'];

Using the time statically, as shown above, can be great for an entire application, however, sometimes you just want to implement a timer within a specific class. In this case, you might consider using the the timer for internal class use only.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class My_Class
{
    public function __construct()
    {
        Script_Timer::start();
    }

    public function my_Method()
    {
        // do something
 
       echo Script_Timer::get() . ' seconds';
    }
}

Development, PHP, Uncategorized , , ,

Modular CSS with PHP

August 1st, 2008
Comments Off

As a web developer, you are often told to keep the presentation layer separate from the logic, data, etc… It becomes frustrating to implement good CSS, especially in modular, OO programs. Many developers bang their heads against their desk with CSS implementations. This has been a frustration for me as well. There are some great ways to keep your CSS contained with your program and still keep it flexible.

A PHP class, in my mind, should be something that can be independently deployed in ANY application, unless it is application specific. There are cases when the code is application specific or there is no need for the developer to control any aspect of the visual implementation. Either way, you want to try and build it so it doesn’t depend on accessing outside assets directly. For example, you want to try and keep your class from accessing external constants, globals, even styles. A more flexible exception to this is environment variables. Ideally, the value of $_SERVER, $_ENV or other Apache variables, should be passed in to your class, however, sometimes it could make more sense to access them directly from inside the class. This usually isn’t a problem because the value normally exists.

Styles and other visual elements become a challenge because they don’t exist in the PHP environment and you can’t feasibly pass in every possible visual element like this:

1
2
3
4
5
6
7
8
9
10
11
12
$thingy = new Widget(
    $var_1,
    $var_2,
    '#000044',
    'center',
    'bold',
    'right',
    'solid 2px #eeeeee',
    'Arial, Verdana',
    '14px',
    '16px'
);

This is just unacceptable and makes for a sloppy API to your program. Plus, you’ll either find yourself adding more arguments as you need more style elements and/or you’ll find that many of the values will always be the same, causing you to pass arguments for nothing.

I will often use an approach that allows me to define the styles in the HEAD of the document, but will still allow me to customize styles at a class level. The “C” in CSS (cascading style sheets) is often ignored. The way they cascade and inherit values can be very useful for a developer if used properly. If you define a DIV tag and give it a class, it will look for that defined class as below:

1
2
3
4
5
6
7
8
9
10
11
<style type="text/css">
.my_style_class
{
    color:#ffffff;
    background-color: #000000;
}
</style>

......

<div class="my_style_class">HTML Content</div>

If you define the style attribute for the element, values in the style attribute override those in the class:

1
2
3
4
5
6
7
8
9
10
11
<style type="text/css">
.my_style_class
{
    color:#ffffff;
    background-color: #000000;
}
</style>

......

<div class="my_style_class" style="color: #ff0000; background-color: #ffffff;">HTML Content</div>

The benefits of this approach can be utilized programmaticially to accomplish the same thing and offer the flexibility you need within your application. The way you do this is to create default styles in your constructor, and set them to an emtpy string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class My_Class()
{
    // make style available to whole class
    private $style;

    function __construct()
    {
        // set default styles representing the class equivalent
        $this->style = new stdClass();
        $this->style->outer_box = '';
        $this->style->control_box = '';
        $this->style->top_html_section = '';
        $this->style->bottom_html_section = '';
    }
}

Adding a method to set these values you can set the style values to any CSS allowable string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * Overwrite default style values
 * 
 * @param STRING    css_class   string name of config value to overwrite (corresponds to css class for that item)
 * @param STRING    style       value to overwrite configuration
 *             
 * @return BOOLEAN  success of overwrite
*/

public function set_Style($css_class, $style)
{
    $success = true;
    if(isset($this->style->{$css_class}))
    {
        $this->style->{$css_class} = $style;
    }
    else
    {
        $success = false;
    }

    return $success;
}

Internal to your class, you then fill HTML style attributes with the internal class values and you also assign them a class by the same name:

1
2
3
4
5
6
7
8
9
10
11
12
13
public function display_Html()
{
    $html = '
        </p><div class="outer_box">
            <div class="control_box">Control buttons</div>
            <div class="top_html_section">Top HTML</div>
            HTML Content
            <div class="bottom_html_section">Bottom HTML</div>
        </div>
    '
;

    return $html;
}

Bringing this all together, this is how it would be implemented. First the PHP class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class My_Class()
{
    // make style available to whole class
    private $style;

    function __construct()
    {
        // set default styles representing the class equivalent
        $this->style = new stdClass();
        $this->style->outer_box = '';
        $this->style->control_box = '';
        $this->style->top_html_section = '';
        $this->style->bottom_html_section = '';
    }

    /**
     * Overwrite default style values
     *  
     * @param STRING    css_class   string name of config value to overwrite (corresponds to css class for that item)
     * @param STRING    style       value to overwrite configuration
     *
     * @return BOOLEAN  success of overwrite
    */

    public function set_Style($css_class, $style)
    {
        $success = true;

        if(isset($this->style->{$css_class}))
        {
            $this->style->{$css_class} = $style;
        }
        else
        {
            $success = false;
        }

        return $success;
    }

    public function display_Html()
    {
        $html = '
            <div class="outer_box">
                <div class="control_box">Control buttons</div>
                <div class="top_html_section">Top HTML</div>
                HTML Content
                <div class="bottom_html_section">Bottom HTML</div>
            </div>
        '
;

        return $html;
    }
}

Then the actual PHP page that handles the display:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<html>
<head>
<style type="text/css">
.outer_box
{
    color:#ffffff;
}
.control_box
{
    color:#ffffff;
}
.top_html_section
{
    color:#ffffff;
}
.bottom_html_section
{
    color:#ffffff;
}
</style>
</head>
<body>

<?php
$new = new My_Class();
$new->set_Style('top_html_section', 'color: #000000; font-size: 16px;');
$new->set_Style('bottom_html_section', 'color: #000000; font-size: 16px;');

echo $new->display_HTML();
?>

</body>
</html>

Now by default, the ‘outer_box’ and ‘control_box’ style classes will be applied to their respective elements. However, ‘top_html_section’ and ‘bottom_html_section’ will now be overwritten with the style attribute with larger black text from the $new->set_Style() method call.

You now have the ability to control your styles via style classes, style attributes or a combination of both, allowing for independent use of the PHP class within your program if necessary.

PHP, UI , ,



Sponsored Links



agile ajax black hat Cake PHP centering clifford stoll css cuckoo's egg energy energy drinks espionage flash Flex hacker jquery modular MVC objects optimization performance PHP script timer smarty smarty templates stylesheet up-time uptime variable scope web 2.0 Zend Framework