PHP


I learned something new the other day while studying for the PHP 5 Certification exam and when I actually read the docs on php.net for array_push I found the same tip:

Using

$arr[] = "blah";

is faster than using

array_push($arr, "blah");

Why? because its not doing a function call. Another thing I learned, and a good use of array_push is when you have multiple items to add to the list

array_push($arr, "blah", "crap", "need more coffee");

In that case, I think it may be faster to do that then to do a for loop and add the 3 items individually.

Just a little something I thought I’d pass along .. :)

Well last night a another good turn out at the Chicago PHP User’s Group meeting (We don’t yet have a short, cute name like chirb or chipy, besides.. how would one pronouce “chiphp” … ch-PUH-ph or just ch-PUH ?) … we had about 17 people show up.

Jason Rexilius gave a presentation on “Elements of a globally distributed HA cluster” .. Although I hope to never have the responsiblity of such a system, it was interesting to me as a developer to see some ideas on how such a system could work.

I asked about this…

Say a company has 9 smaller offices and 1 main office. You have a database web application. You want to make sure that if the main office goes down, the individual offices can still access this application. One theory is to have all databased reads come from the local copy of the database and all writes go to the main office database. Then perodically the main office database will update all the smaller office databases.

Jason suggested that the local office could write to its own database and also write to the main database if connection is available.

But for database keys… I’d have to have one master way to make sure each record created some where has a unique key. I guess one way is to have a master sequence table on the master server, and to save .. the office database would have to get the ID. If no connection was available…then.. I suppose it would have to go into a log until such a time the master database was available. Interesting discussion ….

Anyways…after the presentation Larry attempted to fix my borked install of Kubutu, but I guess a reinstall is in order. Since I missed my 9:20 train by about 20 mins, Rich, the group leader drove me back to the loop and we got coffee/ice cream at Dunkin Donuts and talked for a bit till I could catch my train.

Fun times ..

Checkout BarcampChicago that Jason is organizing!

I think this is the biggest Chicago PHP Users Group meeting I’ve been a part of, I believe I counted 15 people in attendance. Attendees were left to entertain themselves with pizza, beer and conversation while Rich, few others and I dealt with the technical difficulties so common at these things. Which would of probably been minimal if I had remembered that on my Uber Cool Laptop, I have no archaic VGA port – but only a DVI port and my The full dongle was sitting at home! DOH. So, we tried to load my files to my thumb drive which when plugged into Rich’s cute little laptop…didn’t like to read. DOH. So I tar-gz my files and ftp to my server.. then attempt to download to Rich’s laptop. His laptop wouldn’t untar the files. DOH.

So I put my font size real big on my laptop and set up on a stack of books and said lets go with a 17 inch widescreen display and offered my glasses to anyone sitting on the back. I have a sweet screen thats easily viewed from all angles.. so I guess it was not too bad. Better than nothing or using mime to present AJAX. Which I did in college. For all of 3 weeks.

Although I don’t think anyone present was unfamiliar with AJAX, I showed Google Maps, a Sudoku creator/solver and TurboDB. Someone mentioned Weboggle and explained how that worked and I went to the site so folks could see.

I started with the method I use when I learn something new. I start with the most simple example, then build on it. The first example was just loading a plain text file via AJAX and displaying in a div. From there, I did an example calling a PHP file that created a list of files. Then I introduced Prototype, a Javascript AJAX library that makes the code so much cleaner and easier to use. Its include with Ruby on Rails, but you can download and use it totally seperate. The Ruby Kids can’t have all the fun! Some of them had not seen the uber cool $() function that Prototype gives Javascript. Its essentially this;

function $() {

var elements = new Array();

for (var i = 0; i var element = arguments[i];

if (typeof element == ‘string’)

element = document.getElementById(element);

if (arguments.length == 1)

return element;

elements.push(element);

}

return elements;

}

(cut and pasted from prototype 1.5)

so instead of

document.getElementById(‘messageID’).innerHTML = ‘foo’;

you can simply use

$(‘messageID’).innerHTML = “foo”;

It takes either a string of an id, or an array of ids and returns the object reference to them (or array of references). Now why didn’t I think of that. Nifty.

Folks pointed out that the property “innerHTML” might not be 100% cross browser (Heck with that, if it doesn’t work in Firefox, eat my shorts!) and that you should use appendChild. You have been advised.

I illustrated the Ajax.Request object, that allowed you to set a function to call when the data is loaded, and a function to call if there is an error. The Ajax.Update object takes the name of the id to display the results in, and a function to call if there is an error. Most of the time, all I want to do is display some result in a div, so I use this one. Someone in the group said that Ajax.Request was all they used.

NOTE: Remember to use keyword “new”. So you won’t be like me, in a near panic 3 hours before presenting trying to figure out why I’m so dumb that my simple AJAX thing doesn’t work. Error message in Javascript console: “this.initialize has no properties” Line 20 in prototype.js. HUH?! I should of remembered to search Google with my error message first thing.

Like this:

var result = new Ajax.Updater(

‘messageID’,

url,

{

method: ‘post’,

parameters: “color=”+text_color,

onFailure: reportError,

});

NEW NEW NEW NEW … maybe now I’ll remember. Or in 2 weeks google for my error and find this post.

Then I showed what would happen if there was an error. My error reporting consisted of dumping the ugly http error in an alert box. Not recommended for production.

Finally, I showed a simple example of sending a value with ajax to a php file which returned a result. Which Larry was quick to point out was not checking the variable from the user.

Well of course. I am smart enough not to XSS myself in front of a room full of geeks. :P

Oh and thanks for the swag “Harper The Amazing” brought from his company ExtraTasty.com .. shot glasses and tshirts … awesome!

Sample Files from Presentation:

ajax.tgz
ajax.zip (for you windows peeps)

Links

Prototype

Prototype Documentation

edit: fixed link to ExtraTasty.com

PHP in the Federal Enterprise and the World: Secure Solutions for Federal Agencies, IT Companies and Non-Profit Organizations

We are hosting the first DC Metropolitan area PHP Conference this October. Not only that, but since we’re in a unique location with opportunities and potential impact like nowhere else in the world, we’re taking a slightly different look at PHP. Our mission is to demonstrate and teach how PHP is a solid, sensible, cost-effective, and low risk development language to use for government and non profits.

Therefore, our Presentation Tracks fall into four areas:

  • Integrating PHP with Federal Operations and the Enterprise
  • Security & Accountability
  • The Art of PHP
  • The Business Case for PHP

The Call for Papers ends on July 7th and gives suggested topics in each of these areas. Your presentation will be up to 400 people including decision makers for some of the largest and most influential organizations in the world.

Additional Information available:

  • As of last week, the Sponsor/Exhibitor Prospectus is available. We are already in discussions with a handful of major players in the Open Source/Government areas, so if you’re considering, don’t wait too long.
  • Also as of last week, the Call for Papers is open. As noted on the first page “Overall, strong preference will be given to sessions where real projects, actually deployed in business settings, are used to illustrate the topics being discussed”. Translation: If you are successfully using PHP in a production environment in a government agency, you will be given special attention.
  • For those interested, we will have banner available which you are welcome to share, post, etc:

If you have any questions or comments, don’t hesitate to drop a note to (keith at CaseySoftware.com).

Update: Chris Shiflett posted an informative reponse on Test-More for PHP and testing in general

I started responding to the comment to my last post, then realized it was going to be long. So I put it in a post.

Thanks Damien Gilles, I have looked at that. Problem is, I have some resistance at work to using outside code. So I would need to work up a case for it beforehand and analyize it.

For really simple tests, this sort of testing (my friend Keith calls it Sanity testing) works fine. I don’t really see the need to use a Unit Test framework. I have used PHPUnit before and it works fine, but ends up being just more typing (I think, but I’ll try it and compare my results).

Here’s an example of how I used it..

include_once("config.php");
include_once("User_Model.class.php");

$t = new Test_Simple(array("tests" => 20, "eol"=>" n"));

connect_db();
test_setup();

// Test object get/set methods
$user = new User_Model();
$user->setUserName("jdoe");
$user->setRealName("John Doe Test");
$user->setEmail("john@doe.com");
$user->setPermission("1");

// test true values
$t->ok( $user->getRealName()   == "John Doe Test", "get RealName" );
$t->ok( $user->getUserName()   == "jdoe", "get UserName" );
$t->ok( $user->getEmail()      == "john@doe.com", "get Email" );
$t->ok( $user->getPermission() == 1, "get Permission");

// test false values
$t->ok( $user->getRealName()   != "Susie Doe", "Not Realname Suzie Doe" );
$t->ok( $user->getUserName()   != "sdoe", "Not Username sdoe" );
$t->ok( $user->getEmail()      != "suz@doe.com", "Not email suz@doe.com" );
$t->ok( $user->getPermission() != 0, "Not Permission 0" );

// Save user
$saveResult = $user->save();
$t->ok( $saveResult == true, "Save was successful");

// Get ID of last user
$id = $user->id;

// clear object
$user = null;

// load user again and test again
$user = new User_Model($id);

// test true values
$t->ok( $user->getRealName()   == "John Doe Test", "get RealName after load" );
$t->ok( $user->getUserName()   == "jdoe", "get UserName after load" );
$t->ok( $user->getEmail()      == "john@doe.com", "get Email after load" );
$t->ok( $user->getPermission() == 1, "get Permission after load");

// change username
$user->setRealName("Mary Jane Test");
$user->setUserName("mjane");
$user->setEmail("mary@jane.com");
$user->setPermission("2");
$updateResult = $user->save();

// test true values
$t->ok( $updateResult == true, "Update was successful");
$t->ok( $user->id == $id, "ID stayed the same");
$t->ok( $user->getRealName()   == "Mary Jane Test", "get RealName after update" );
$t->ok( $user->getUserName()   == "mjane", "get UserName after update" );
$t->ok( $user->getEmail()      == "mary@jane.com", "get Email after update" );
$t->ok( $user->getPermission() == 2, "get Permission after update");

$deleteResult = $user->delete();
$t->ok( $deleteResult == true, "Delete was successful");

test_teardown();
$t->report();

// Clean up our mess before and after
function test_setup() {
connect_db();
$result = mysql_query("DELETE FROM users WHERE real_name like '%test%'");
}

function test_teardown() {
connect_db();
$result = mysql_query("DELETE FROM users WHERE real_name like '%test%'");
}

I did do a test_setup and test_teardown, similar to what you would have in a unit test. I only need to do this at the start of my “suite” and the end.

Of course, the main reason there’s a test more (copied from Perl) for php is so you can use Perl to run the test suites. See this presentation by Geoffrey Young and Chris Shiflett on Power PHP Testing(tgz file) which, if you have a site with mixed PHP and Perl, would be a excellent way to test all your code with the same method.

My two loyal readers know I like testing. Some say I’m sick.

I’m writing a PHP class for a user, and then think.. oh gee, how do I know if this works?? oh I’ll write a Test::Simple for PHP. Yes, I know there exists one already that uses the power of Perl to test PHP files, but I didn’t have time to figure out how to set that up and probably won’t be able to use perl anyways on the production system. I can’t stand to have global variables, so I made a class. Uber simple. There’s probably better ways to do it (I can imagine something much more elegant in PHP 5). But, what do you expect on a whim and 40 minutes…

Code:

// Nola’s Wanna Be PHP Test Framework

class Test_Simple {
var $tests_to_run;
var $success_count;
var $failure_count;
var $test_count;

function Test_Simple($params) {
if (isset($_SERVER['HTTP_HOST'])) {
// we’re on a server use a

$params['eol'] = “\ n “; //take out spaces, had to have them for this blog
}
$this->tests_to_run = $params["tests"];
$this->eol = empty($params['eol']) ? “\n” : $params['eol'] ;
$this->success_count = 0;
$this->failure_count = 0;
$this->test_count = 0;
print “1..{$this->tests_to_run}{$this->eol}”;
}

function ok ($expression, $message) {
$this->test_count++;
if ($expression == false) {
print “not “;
$this->failure_count++;
} else {
$this->success_count++;
}
print “ok {$this->test_count} – $message” . $this->eol;
}

function report() {
print $this->eol;
if ($this->test_count tests_to_run) {
print “You ran {$this->success_count} out of “
. “{$this->tests_to_run} tests ” . $this->eol;
} else {
print “Opps, looks like you meant to run {$this->tests_to_run} “
. “tests but ran {$this->test_count} instead” .$this->eol;
}
print “Success Rate: “
. (($this->success_count *100)/ $this->test_count)
. “%”.$this->eol;
}

}

And.. I made some code to test itself..

$t = new Test_Simple(array(“tests” => “4″));

$t->ok($t->test_count == 1, “one test run”);
$t->ok($t->tests_to_run == 4, “running 4 tests”);
$t->ok($t->eol == “\n”, ‘end of line is \n’);
$t->ok(true, “its true!”);
$t->ok(!false, “its not false”);

$t->report();

I will probably make improvements upon this… suggestions? .. my test “report” is a bit more verbose than the standard Test::* in Perl.

I made it so you can run it with the php executable … or with the web browser.

I tried to install Perl’s class Apache::TestRunPHP but had a few problems getting it setup on windows. I think I need mod_perl installed on my Apache. I did find out that it takes a different approach than my simple class, and starts apache, runs tests, prints report and shuts down apache. Interesting. My tests I only intended to run individually (actually didn’t know how TestRunPHP worked till after I wrote my class).

when you don’t keep your big mouth shut (and leave before meeting is over)?

Email sent to PHP Group after meeting:

At the end of our meeting Wednesday, several Topics / Speakers were planned out for coming months. WED FEB 15 Sara[h?] | Smarty WED MAR 15 Rich | PHP5 SOAP WED APR 19 Nola | We volunteered you to talk about, ummm, something you seemed to know a lot about at the meeting that I forgot already... Sara[h?] e back so I can spell your name right on the website. Anybody remember what we volunteered Nola to do? Is Nola willing?
Yes.... Nola is willing. I was talking about XmlHTTPRequest, AJAX and the Prototype library.

I don’t know where this idea settled into my little head, probably back in college. I sold practically every book from my college days, keeping only a few books (For anyone who had a blue book by Blum with a picture of driftwood on it for Software Engineering, you have my sypathies. Can’t believe its still $97 bucks) so I can’t look back to see if any of my classes was the culprit (could it be java? it sure wasn’t assembler!). I have always defined get/set methods for my classes with get/set in the name.

class Card {
var $name;

function set_name($name = "") {
$this->name = $name;
}

function get_name() {
return $this->name;
}
// etc
}

I’ve seen some people do this:

class Card {
var $name;

function name($name = "") {
if (empty($name)) {
return $this->name = $name;
} else {
$this->name = $name;
}
}
// etc
}

Using the same method for getting or setting, the deciding factor is if a parameter is passed.

I mentioned this in a Codesnipers post about how Ruby does get/set for attributes. Caleb Tennis showed a way I could customize the get/set methods of Ruby so it DOES allow you to do getName or setName.

My recent language crush is Perl, and I’ve seen many modules doing it the second way.

But “name” isn’t a function so I don’t really like doing it the second method. But is it an “okay” convention that I should wave a white flag and accept? I guess I could look at it this way, if a function name is just a noun, then it’s for an get/set method, if not then it’s a regular method.

Should I change my mind on this? what do you do?

I found something out I didn’t know the other day, while writing a blog entry for CodeSnipers.com a wealth of information for coders of all types! I so happen to be the only one writing about web development at the moment, but hey we can all learn from each other – right? Checkout the php echo stuff… anybody besides me didn’t know you could do echo $var1, ‘ ‘ $var2;

I am very interested in Ruby and “Rails”. I am going to do a series of comparisons of php and ruby on CodeSnipers — stay tuned! First entry was how to display output .. and Ruby has some nifty things like $\ and $, for formatting, read more Here!!

Frustrated at my “day job” … I constantly have the need for DAO’s and well I started a blog post about it. Basically, I am unable to use premade DAOs and find it most most extremely frustrating to have to write my own when already exists some.

I am looking for a new job, PHP / MySQL developer. Let me know if you hear anything. Bah.

I don’t like programming by myself. At my job, I am the lone programmer. My boss meddles around a bit, but as he is responsible for about 50 other things, he doesn’t get to do too much. I had a co-worker for 1.5 years, and that make work more enjoyable and I was able to bounce ideas off him, when I got stuck he could see my problem etc. This also applies to other situations as well. Two candy bars are better than one. Two beers are better than one. Two dollars are better than one. I’m better married to Mr. Nick. :)

Today Ivan asked if I’d like to work on some small projects together, something to the effect of “Extreme Programming” methodology. I said that would be great! We are both doing some work for Casey Software which is great as well. I want to perhaps work on a Order module for Dot Project or work to improve the existing Inventory Module. I just am nuts about the framework — its not perfect, but the coding is very nice, well built (and I’m picky) so it makes it more fun to work with. :)

Link of interest to me today: Smarty as a sub language – I like Smarty. I can also see the side that php can itself be a templating engine.

Check out the latest Pro-PHP Podcast – PHP news

Listening to: George Thorogood and the Destroyers (Get a Haircut and get real job! Clean your act up and don’t be a slob. Get it to together like your big brother Bob! why don’t you get a haircut and get a real job!)

« Previous PageNext Page »