Archive for the ‘PHP’ Category.

CyTS library stalling

On our guild website, we have a block in the portal that shows who is currently on teamspeak. This uses the CyTS library to connect and get such information and occasionally it would cause the portal to stop loading.

In each case I would get home, load it up and not find any problems at all. Well today was a different matter, I was able to pin point the exact issue. For some reason the library connects to the server but then stalls when receiving information from the server.

I should tell you know, this is not a perfect fix but it does the job. I did look into other options like switch socket blocking on and off and such other approaches, but it seems that if fgets reads more than 1 byte, it stalls. This is a bug in PHP that has hung around for a while.

I have changed the _readcall function to read the first byte, check it for failure then continue with the rest.

function _readcall()
{
	if (!is_resource($this->sCon))
		return false;

	// HACK : Workaround to fail fast
	$first = fgets($this->sCon, 1);

	if($first === false)
		return false;

	$sRead = '';
	do
	{
		$cRead = $first.fgets($this->sCon);
		$first = '';

		$sRead .= $cRead;
	} while ($cRead != CYTS_SYN && $cRead != CYTS_OK && strtoupper(substr($cRead, 0, 5)) != "ERROR");
	return $sRead;
}

Unit Testing with NetBeans and phpUnit

Huzzah! I have found a way of being able to run the Unit tests in NetBeans.

Since phpUnit is essentially a set of php scripts itself, I thought to myself there must be a way of invoking it.

What I did was setup a source file as the boostrap for the Test Runner, set this file as NetBeans index file and from there you can just run it and see the test results in the output window or debug and it step into the test you are interested in.

It is not a fantastic solution but it is definately a stop gap until they do implement php Unit testing.

Heres my boostrap file for running tests:

<php
$args = array(
__FILE__,
"--coverage-html",
"D:\\Logaan\\Documents\\XamppData\\htdocs\\FormManager\\CodeCoverage",
"--verbose",
"D:\\Logaan\\Documents\\XamppData\\htdocs\\FormManager\\tests\\TestSuite.php"
);

$_SERVER['argv'] = $args;
$_SERVER['argc'] = count($args);

require_once 'PHPUnit/TextUI/Command.php';

// Exclude this file from code coverage
PHPUnit_Util_Filter::addFileToFilter(__FILE__);

?>

Its very simple, what I am doing is hard coding my arguments into the server environment variable (you could use the arguments in the NetBeans configuration) which is where phpUnit gets the arguments from.
Including the phpUnit TestUI test runner which has the main entry point, excluding this file from code coverage and then I just sit back and l let phpUnit run its course.

This is only a work around until Netbeans supports phpUnit.

NetBeans IDE

The other day I had hit a brick wall, I was really struggling with part of my FormManager project and really needed to debug it.

I started looking into XDebug and discovered what it could really do, and diving into the website I found they listed a set of compatible IDEs that could use the extension to debug php. Since I had spurned eclipse I thought there was nothing else short of the Zend IDE that could help. Thats when I noticed NetBeans. The last time I had used NetBeans was back in college for some Java projects. I was really surprised when I found out that they offered a PHP IDE.

Within a couple of seconds of getting the project setup in the IDE it found the problem already for me. It does a much better job of context sensitive variables than Eclipse ever did, and it can pick up all kinds of problems much better than Eclipse, within a few minutes I had fixed the problem and even found a couple of problems that I did not yet know about.

It even includes some basic refactoring tools!

NetBeans does support Unit Testing however there is currently no support for phpUnit at this time. It is planned as a feature some point in the future.

Form Manager

I finally found a decent name for this “DynamicDataModel” project I have been working on; Form Manager.

Synopsis: A set of objects to allow the developer to write as little code as possible to instantly get a form with validated fields and basic data manipulation.

My idea to was to write something that would allow me to quickly describe what data I want to edit/display, have a standard mechanism for verify data from the user and a generic method of talking to a database to create/get that data.

So far this is what I have come up with:

I built the diagram in NClass, but I kind of cheated and built the model in C# and imported it

The modes know how to render the data, where the data needs to come from and at what time.
The fields are quite the opposite, they know where the data is, and what to do with it, but don’t know when to use it.

So I built this model, the TableDefinition and FieldSet have all the fields hanging off them. And the relevant modes are hanging off the FormManager.

Although I plan to integrate this into phpBB, I have put in layers that should allow for this model to be used in anything.

The other thing is that I am trying to build in as little state as possible so that it can be cached to improve speed. However this will be seen once I start using it in more realistic situations.

The only wierd thing about the model that I am not completely happy with yet is that when the field is told to render itself, it is given the data to use.

I have unit testing around it all, and generated documentation so once its finished I should have quite a nice comprehensive application.

Documenting your code in PHP

Whilst working on this model, I found myself forgetting various parameters or names of methods I had created. I can’t believe how much I rely on an IDE to provide me with all my prompts.

I did try setting up Eclipse again with PDT (had tried to use phpEclipse in the past with dissapointing results) yet I was getting UI errors all over, no matter what I tried (updating the JRE, grabbing various packages) I could not get the thing to work.

So I resorted to the next best thing, I went and found something called phpDoc. It reads DocBlocks from your code and creates a set of html pages containing all the information about your code.

Again, I installed it from pear on the command line, there are lots of site out there to help with installing it on Windows. Once installed, you can use the phpdoc -h to get all the command line parameters.

Similar to my last post, I use an msbuild script to run the documentation tasks


<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">

    <PropertyGroup>
        <BuildDir>$(MSBuildProjectDirectory)</BuildDir>
        <DocumentationTitle>Dynamic Data Model</DocumentationTitle>
        <HelpOutput>HTML:Smarty:HandS</HelpOutput>
        <DocumentationFolder>$(BuildDir)Documentation</DocumentationFolder>
    </PropertyGroup>

    <ItemGroup>
        <CodeFiles Include="$(BuildDir)***.php" Exclude="$(BuildDir)**.svn***.*;
                                 $(BuildDir)**tests***.*" />
    </ItemGroup>

    <Target Name="Clean">
        <RemoveDir Directories="$(DocumentationFolder)" Condition="Exists('$(DocumentationFolder)')" />
    </Target>

    <Target Name="Setup" DependsOnTargets="Clean">
        <MakeDir Directories="$(DocumentationFolder)" Condition="!Exists('$(DocumentationFolder)')" />
    </Target>

    <Target Name="Build" DependsOnTargets="Setup">
        <CallTarget Targets="BuildDocumentation" />
    </Target>

    <Target Name="BuildDocumentation" DependsOnTargets="Setup">
        <CreateProperty Value="@(CodeFiles, ',')">
            <Output TaskParameter="Value" PropertyName="FilesToDocument" />
        </CreateProperty>

        <Exec Command='phpdoc --sourcecode --target "$(DocumentationFolder)" --output $(HelpOutput) --title "$(DocumentationTitle)" --filename $(FilesToDocument)' />
    </Target>
</Project>

Unit testing in PHP with PHPUnit

With this dynamic data model that I am currently building in PHP, I found that for quite a complicated solution I had no unit testing at all.

After searching around I found PHPUnit, however, it all hinted at a Linux only environment. A short while later I found a blog that described how to set it up for Windows: http://usingzendframework.blogspot.com/2007/12/setting-up-phpunit.html. I use Xampp, so I did not have to change the memory limit.

Once installed I used the online pocket guide to start me off: http://www.phpunit.de/pocket_guide/index.en.php

Inside my code folder I created a tests folder where I placed all my php tests, inside that I created an includes folder for all the test related code.

folders.jpg

The first thing that the common include does is turn on all the error reporting an strict reporting. This should ensure the most quality coding.

<?php
error_reporting(E_ALL | E_STRICT);
require_once('PHPUnit/Framework.php');
?>

Once that is done, I could start with writing all the tests.

<?php
include('includes/common.php');
class ExampleTests extends PHPUnit_Framework_TestCase
{
 public function testSomeObjectTest()
 {
  /* Test code here */
 }
}
?>

Once that was done, I created a msbuild script to test them all using the TestSuite class

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
    <PropertyGroup>
        <BuildDir>$(MSBuildProjectDirectory)</BuildDir>
    </PropertyGroup>

    <ItemGroup>
        <CodeFiles Include="$(BuildDir)***.php" Exclude="$(BuildDir)**.svn***.*;
                                                           $(BuildDir)**tests***.*" />
    </ItemGroup>

    <Target Name="Build">
        <CallTarget Targets="RunTests" />
    </Target>

    <Target Name="RunTests">
        <Exec Command='phpunit --verbose "$(BuildDir)testsTestSuite.php"' WorkingDirectory="$(BuildDir)tests" />
    </Target>

</Project>

I had to add the framework folder and the php folder onto the PATH environment variable so that I could just call msbuild from the commandline

Data driven pages generated from described data

Over the last couple of projects I have done in php (usually related to phpBB) I always seem to follow the same patterns. List data, edit data, add data… and every page follows the same pattern; check mode, validate inputs, write to database… etc etc

 So I thought I would look for a framework that would allow me to describe my data in such a way that it will go off and automatically query the data, join data from lookups, check data inputs, update the database and generate all the pages and forms for me.

Alas I did not find any such projects on the internet (so I am going to have a crack at it myself) but I did find this project: https://www.projectzero.org/

Its a bit over developed for what I want to achieve, still sounds pretty neat.