PHP SPL autoload: 3 simple rules you must follow
September 29th, 2008 by Aaron
While working on a larger site that I may need to use many external libraries, I realized I need to come up with a better __autoload() function (for example, I think it was DOMPDF that had its own autoload function as well. Last time I used that, I had to hack my own autoload to use their code as well to locate files). I researched into SPL autoload functionality, and I’ve found what I need. Through some trial and error, I found out 3 absolutely necessary rules that need to be followed when building your custom autload functions, however. Lets examine:
Continue reading PHP SPL autoload: 3 simple rules you must follow
CSS incompatibility finder
September 25th, 2008 by Aaron
This is more of a proof of concept than anything else - as most of my scripts are
But, lets say you have some files that have css in them, either external stylesheets, internal one with style tags or even style attributes - and you need to update the browser support. Wouldn’t it be great to have a tool that could look through these files and point out that there are incompatibilities?
Well here is such a script!
Continue reading CSS incompatibility finder
Anti Spam Solution for small / medium business?
September 22nd, 2008 by Aaron
One of the biggest internal battles I have is whether to host my email locally on my 16mb/2mb network, source it out to the web host, or use a specialized webmail company. I like that feeling of control, the fact that I know I could set up any anti spam and virus filtering service I wanted if I fully controlled my e-mail. However, if my internet service goes down, or I have a power outage, no email! I’ve always liked to tinker with my own servers as well - but I think getting a full rack mount solution is just outside of my budget.
Solution for Small to Medium sized Businesses
Enter Perimetec. Perimetec’s combination of products and services was one of the main reasons why I spent so much time on their site when I first visited it. First off, their Email Spam Blocker service looks pretty cool. For $2.50 a month per mailbox, I can get usage of this service -basically an account on their Barracuda appliance. (Looks like you can get a discount if you sign up for a year.) Not only will this provide me with top of the line spam filtering, it will even queue email if my service goes down. (Hrm… Maybe I should start looking at that whole closet set up I have again… can that old 450mhz box handle my mail load?). Add-ons to the service include DNS management and Webmail.
Products for those with their own systems
If you’re more on the ball than I am, and have everything all set to go in your closet/computer room/server farm, then check out Perimetec’s Barracuda Anti Spam products. Touting what appears to be the full line of Barracuda products, it looks like Perimetec’s in a good place to offer good deals on their line.
What would I do?
Lets be honest - free trials are awesome - but they’re usually short. Too short. Perhaps you’ve not even had a chance to use a Barracuda product before either. Whether you’re just a small business or looking to get your own system, sign up for the service first. For $2.50 a month on an email account, you can check out the type of service your own appliance will give you. Then, when you’re ready to take beef up your Email Spam Protection, definitely consider upgrading with Perimetec.
SVN Pre-commit duty: Lint your PHP
September 21st, 2008 by Aaron
We’ve all been there before, committing code - and then realizing that it was broken (hrm - our unit test didn’t catch it? or… “what unit test?” if you’re in another environment). Well, there is a solution.
Batch File Fun!
Since I dev primarily on windows, I wrote a batch file. You can also write a linux script using awk in bash (or insert your fav shell here) that will do basically the same thing. From now on, especially at #superdev, I’m going to run “lint.bat” before I commit:
lint.bat
1 2 3 4 5 6 7 8 9 10 | @echo off echo. echo Starting SVN Stat + PHP Lint echo ============================ svn stat |findstr /I /R "\.php$ \.phtml$" >lint.txt for /F "tokens=2 delims= " %%i in (lint.txt) do php -l %%i |findstr /I /B /V "No syntax errors" del lint.txt echo. echo ============================ echo Finished SVN Stat + PHP Lint |
So what is happening?
Basically, when you run “lint.bat” in the root of your repository, you’ll see a start and end message. If you’re lucky, nothing will be between the two double bars. If you’re not lucky, then you know what you need to fix before you commit. But, here’s what is really happening:
Basic Batch File Stuff
Turn off the command echo (@echo off), and print some context (starting the test).
SVN stat of PHP files
Run an SVN stat and grab files that end with .php or .phtml. If you have other files that need to be ran through the php interpreter, you can add them, space delimited, in this “almost” regular expression format. Note the “$” which signifies that the pattern match should be at the end of the string. Output this to a file called ‘lint.txt’ - hopefully this not part of your code repository!
Loop through and look for syntax errors
Loop through each line of that stat file and run the php interpreter against it. If the message does not begin with “No syntax errors”, display the error message to the console.
Clean up and end
Delete the lint.txt file, and then finish up by printing some nice message and double bar.
Things to remember
Both ’svn’ and ‘php’ should be in your system path. Also, the user who is running the lint.bat file should have permission to write files into the current working directory. Finally, if you have more than .php and .phtml files, modify the regular expression to find all of the files that need linting!
Don’t focus me, bro!
September 20th, 2008 by Aaron
I hate filling out login forms to discover that half of my password is in the username box. Lets talk about why - and then a solution.
Why?
Slow Loading Pages
Slow loading pages, or sites with a lot of content on the login page (see: a no-no for login pages), take a while to finish loading the content. The ‘onload’ handler is usually the whole on-load and not just the domloaded event. Tons of extra content delay the onload handler.
Dialup
Yes, people still have this. Even with the smallest amount of extra content, dialup users will experience some delay.
So what is happening?
People who jump the gun - like me (and 93% of everyone else) are clicking in the username box, filling it in, and then tabbing to the password box. While typing in the password, the page finally finishes loading, and focuses the username. We don’t notice, so we keep typing.
What is the solution
Quickly: activeElement
Firefox 3, and IE4+ support activeElement. (there are other ways around this for other browsers - see the end of this article). Check to see if the body is the active element - before focusing the username. If it is, means that they haven’t started typing anywhere.
Give me an example?
Ok! You should use a better ‘onload’ handler - but I’m being lazy just for this example.
1 2 3 4 5 6 | function loginFormInit() { if (document.activeElement == document.body) { document.getElementById('username').focus(); } } |
1 2 3 4 5 6 7 8 | <body onload="loginFormInit()"> <h1>Login</h1> <form> username: <input type="text" id="username" name="username" /><br /> password: <input type="password" id="password" name="password" /><br /> <input type="submit" /> </form> </body> |
Oh Noes! I need to support more than IE4 and FF3
No worries, citizen! If you need to support something else, besides those two lovely browsers, you could write a function to getElementsByTagName(’input’) and add an onfocus element. That element could set a global variable to ‘true’. Finally, your onload function could check to make sure that that variable is not true - and then do the focus.
To clear up that confusion about public and public static access in PHP
September 19th, 2008 by Aaron
Apparently, a few programmers I know have been getting confused about access of public, public static variables in PHP classes. I’ve written this example code with the following comments to explain what will work - and what won’t.
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 | <?php class TEST { /** public variable **/ public $pubvar = 'pubvar'; /** static public variable **/ public static $pubvarstatic = 'pubvarstatic'; public function __construct() { /** this works **/ var_dump($this->pubvar); /** this also works **/ var_dump(self::$pubvarstatic); /** this would not - no error **/ var_dump($this->pubvarstatic); } public static function statictest() { /** this works - static accessing a static **/ var_dump(self::$pubvarstatic); /** * this does not work - static has no business accessing a non static class var * generates error: * Fatal error: Access to undeclared static property: TEST::$pubvar */ var_dump(self::$pubvar); } } print "<pre>"; /** for testing __construct() **/ new TEST; /** this works - public static access **/ var_dump(TEST::$pubvarstatic); /** for testing static method statictest() **/ TEST::statictest(); |
dtemplate: dynamic template system for static designed files
September 16th, 2008 by Aaron
One of the biggest time wasters I deal with is parsing out static web designs given to me by designers. They don’t know programming, so they design it with static HTML in mind. Even if you’re using a tool like dreamweaver, updating static pages can be a hassle. Then, a lot of times, they have to remove their ‘lorem ipsum’ text and send it to me - and then I continue to chop it up. Now, I’m talking about smaller 5 to 10 page sites here, not huge sites like JEMDiary or something. However, that idea birthed…
Welcome dtemplate!
The purpose of dtemplate was to read in an existing design from a designer or a static site that already exists, and make certain parts parse-able for replacement content. This way the designer can give the developer a complete xhtml package and move on. As long as the files are verified as valid xhtml, they’re good to go. Then the developer will write whatever programming/content needs to be replaced. It would be even possible for the designer to put basically all ‘lorem ipsum’ if necessary - and it could all be replaced.
How does it work?
dtemplate takes existing URLs and rewrites them to be used in the template. The template then reads in the xhtml files, looks for any specified IDs or classes, and replaces the content. It finally renders the content out to the screen. Any non .html file gets rewritten to be found in the new directory.
Implementation Steps
Its easy to put dtemplate into use. If all else fails, check out the comments in the files.
Create source directory
In order to have the content be read in by the template file correctly, you must make a new folder at the base of the site called dtemplate_sourcehtml. Move all of the files in the current root into that folder.
Modify .htaccess
The last line of the .htaccess file specifies the real URL of the site. In our example, its http://myrx8.local. You need to change this to be your site. Put this in the root of the site.
Add additional files
Place the dtemplate_controller.php, dtemplate folder and the verify folder in the root of the site.
Verify each xhtml file
Before surfing to the site, you should visit http://yoursite.com/verify and upload each file, and check for any id’s and classes that you’d like to replace. This way you know if the file will parse fine and if the required classes and IDs are located in the file.
Modify the dtemplate_build_content() function in dtemplate_controller.php
This function is made to replace any content for your file. It is commented - plus you can see an example in the download. It is recommended that you create your own class(es) and use this function only for adding the content to the template when needed - don’t place all your logic in this file.
Surf!
You should be good to go! If you want, you can remove the ‘verify’ folder.
Example
I’ve included a really simple frames website as an example with the download. This was originally on http://myrx8.local as a test.
Todo and Known Issues
- make sure you don’t have to edit out the website in .htaccess
- support multiple directories for html files.
- is pretty rewrite intensive.
The download
Automatic Backup with SVN on Windows
September 12th, 2008 by Aaron
A while ago, I decided that I needed to have a better backup solution for my file server. After doing some research on various systems, I let my inner programmer take over - in addition to my desire to NEVER LOSE ANYTHING - and I defaulted to use SVN.
I was using a Windows machine as my file server - so I wrote some batch files. I also had SVN installed on the machine. The final touch was adding scheduled tasks.
The setup includes a computer that is always on with windows, svn command line, and 5 directories to monitor for backups.
First thing’s first, do an SVN Checkout
The very first thing I did was make an SVN checkout in all of the five parent directories. This way I can continue to use SVN add, svn commit without any other interaction. Don’t worry, we’ll use recursion!
Create the full list of backups
So, first thing’s first: Create the list of directories that need to be monitored. I made them in this txt file named ’svndirectories.txt’:
1 | D:\pictures D:\storage\videos\misc D:\storage\files\art D:\storage\files\NeverAgain D:\storage\files\Therapee |
Note, all of them are separated by a space. This becomes important in our next batch script.
Schedule the SVN Add
I added an SVN Add batch script at Midnight on sundays. Actually, there are two batch files. I made them separately so that I could invoke a scheduled task - but also run the “add” by hand if need be.
The first file, addsvn.bat:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | @echo off REM ------------------------------------------------------------------ REM - forces adds on all svn files REM ------------------------------------------------------------------ :START REM - Get file to process set direct=%1 echo %direct% echo. :SVNADD svn add --force %direct%\* :NEXTFILE shift if "%1"=="" goto END goto START :END |
That will force an add of each file passed in on the command line. Then, the batch file that I made to be ran from the scheduler will read in the folders from the text file, and run this script. Here is ’scheduled_addsvn.bat’:
1 2 3 4 5 6 7 8 | @echo off REM - This is what should be scheduled to add files to svn repos REM - read in svndirectories.txt for /f "tokens=*" %%a in ('type svndirectories.txt 2^>NUL') do set value=%%a REM - call the addsvn program with all the directories addsvn %value% |
Theoretically, I could have called it with the entire line of files after it, but I wanted to call them separately to handle errors better.
After all of these have been added, lets move on…
Schedule SVN Commit
Just in case I made a huge addition of files, I let an hour pass between scheduled add and scheduled commits. Additionally, I ran the commit every day instead of every week. I figured I’d make more changes than I would make additions.
So first, read in all of the directories again and run the commit. Then, the file to schedule. These are pretty much similar, just different commands:
commitsvn.bat:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | @echo off REM ------------------------------------------------------------------ REM - commits all SVN changes REM ------------------------------------------------------------------ :START REM - Get file to process set direct=%1 echo %direct% echo. :SVNCOMMIT svn commit --message="Auto Backup" %direct%\* :NEXTFILE shift if "%1"=="" goto END goto START :END |
scheduled_commitsvn.bat:
1 2 3 4 5 6 7 8 | @echo off REM - This is what should be scheduled to commit files to svn repos REM - read in svndirectories.txt for /f "tokens=*" %%a in ('type svndirectories.txt 2^>NUL') do set value=%%a REM - call the addsvn program with all the directories commitsvn %value% |
This has worked out pretty well for me. If you see anything I could do better, please let me know!
Why your company needs a System Architect/Analyst
September 10th, 2008 by Aaron
In this post, I’m going to cover what a System Architect/Analyst (SA from now on) is and why you need one.
A System Architect/Analyst is…
A top level programmer with a lot of experience.
Experience is king here. No matter how many theoretical classes or book knowledge, experience can trump all of those. It is just impossible to run into as many situations in the class room as in the real world. This person should be continually updating their knowledge of programming concepts as well as …
Still keeps hands in the code.
A common problem with the SA’s I’ve seen is that their programming time continually declines until there is no more hands on involvement from them. It is still important for an SA to keep their hands in the code, whether it is making quick bug fixes, creating complex algorithms or, at the very least, making shells of classes and methods.
Understands advanced architecture concepts and can implement if need be.
While the current project or code base may not necessarily be in the place where advanced concepts can be applied, the SA should still understand these concepts and be able to apply them in other projects. This helps cement the fact that this individual will be the first person that is consulted on a rewrite… which means…
Knows where the code base is going.
Code bases, for the most part, are more of a living/moving entity than a stable patch based system. There is always a need to add more features while refactoring. The SA should know about where the code is going in order to give design guidance to make the new features partially on the road to the refactored code or a rewrite.
Understands where the company is going
It is important for the SA to understand some of the company’s strategic plans for future development and planning. This way they can make design suggestions about existing projects’ architecture to afford for easy upgrading to the future planned additions. This familiarity is accomplished by working somewhat with the management team or decision makers as well as the project managers.
Why You Need One
Heads off problems ahead of time.
When you have an SA in the mix, a good portion of their time is dedicated to analyzing and thinking about the current projects. Having a good knowledge of all of these projects helps them foresee any projects and take care of them ahead of time. Additionally, with all of this knowledge, they can help make educated decisions without having to bother the stakeholders. A lot of times, however, stakeholders will suggest throwing an SA into the mix for the wrong reasons - to code faster, to push out product quicker, etc. This is never a good idea. Once you pull them away from looking at the big picture, its almost as if you don’t have one - or sometimes even in a worse place than before.
Makes recommendations on how teams can accomplish work.
I’ve covered this before, but it bears repeating. While not actually accomplishing a lot of work themselves, they do get involved in many of the projects and give guidance to the team and team leaders on how to best work in the current constraints as well as plan for the future.
Authority from a technical aspect on how code is finished, peer reviewed.
When teams are having some issues solving something or a peer review doesn’t go right, the SA would be the authority on what is the solution. For example, if one peer reviewer says the code isn’t right but the other feels like it is, the SA, from their experience and other understanding, will resolve that issue immediately.
Analysis first saves work later.
Time and time again, analysis is cut short because there are not enough resources to work on the projects as well as analyze the stuff. Well, just off the bat, if you’re suffering from this problem, it sounds like you’re not putting a lot of emphasis on the analysis - or not learning from mistakes. I can’t point to ANY example where analysis first was the ‘failure’ of the project - but I can name a million where it could have helped or did help (search “software” on google for a million examples). Point being, this SA’s primary responsibility is analyzing past, existing, and future code and ideas. This is an important part of any project’s success. Just like every other skill, with practice, this becomes better. It is important to dedicate a person to this task so they can continue to become better at the analysis as well as protect from any project design misses.
Reduces work for managers.
Since the SA knows both the future plans of the business as well as has an eye for the technical solutions, they can jump in and resolve a lot of questions before they have to get queued against a manager. This is not to say that an SA should be at all responsible for personnel issues or anything - but they can help make snap decisions with the notion of what is best for the company and the architecture.
Do you agree?
I’d love to see any comments talking about if you agree with this summary/description, if you’ve recently acquired an SA and any positive or negatives you’ve seen, or if you have other things I missed. Thanks!
heredoc - time for dead-dead or happy-smile time?
September 8th, 2008 by Aaron
PHP’s heredoc - good or bad? All silly titles aside, lets check out some points.
For those who are not aware, heredoc is the format of creating a large string in PHP that does not need quotation marks of any kind. Read more of the points to understand more about it. Here is an example:
1 2 3 4 5 6 7 8 9 | $sql = <<<SQL SELECT a.*, b.*, c.* FROM aTable a, bTable b, cTable c WHERE a.col = b.col SQL; |
GOOD: No confusing escaping of quotes
With heredoc, you do not need to escape quotes of any kind:
1 2 3 4 5 | echo "<a href=\"blah.php\" onmouseover=\"hoverer('blah!')\">blah!</a>"; /** becomes ... **/ echo <<<LINK <a href="blah.php" onmouseover="hoverer('blah')">blah!</a> LINK; |
While this is a ‘valid’ reason, I think this is just justification for sloppy or error prone programmers - but that is just my stubborn - and probably biased - $0.02.
BAD: Last line must NOT be indented
In order for the heredoc to recognize the closing marker, it must not be indented. If it is indented, it won’t recognize it as the end of the heredoc - and it continues. This messes up coding standards that are based on indentation.
1 2 3 4 5 6 7 8 9 10 11 | function tester() { $thing = TRUE: if ($thing) { print "indented line"; print <<<HTML Here is some html content. notice how the next line isn't indented? that sucks! HTML; print "resumed indentation"; } } |
GOOD: Some editors recognize it and properly syntax highlight
Some editors are able to recognize the heredoc identifier and properly highlight the content - such as the SQL will be highlighted SQL syntax, same with HTML.
BAD: Solid block - so no inline calculations - introduces extra variables
For example, if you have to make an item plural if there is more than 1, with a normal string, you can stop mid creation, do a calculation, and continue on. With heredoc you either need to make two of them - or you have to use temporary variables.
1 2 3 4 5 6 7 8 | $trees = 12; print "I have found {$tree} tree" . ($trees != 1 ? "s" : "") . " in my backyard"; /** as opposed to this **/ $plural = $trees != 1 ? "s" : ""; print <<<BLURB I have found {$tree}{$plural} in my backyard BLURB; |
BAD: Could be used as a crutch for bad MVC programming practices
Generally, when you need to create such a large block of HTML inside of a script (which is one of the main proponent arguments for using heredoc), you may be doing too much HTML generation inside of a logic script. This should be refactored to support a better MVC approach - like putting more of that into a view. (thanks to BigBoy for this point!)
Just like my other 2 pennies I offered, I think this is not the best example / reason. Programmers could still do the same thing by just creating normal strings - no heredoc required.
So - time for dead-dead or happy-smile time?
So far, it looks like its more of a personal preference thing on heredoc. There are no concrete reasons either for or against it that make it something you should love or hate. And, I know everyone was waiting to know - so I’ll say it: my opinion is that heredoc could be removed from PHP6 and I wouldn’t miss it at all ![]()
