Tag Archives: PHP

Gamehole! AJAX and MVC (kindof) Development

XMLHTTPRequest Saved My Life

Development with AJAX is pretty easy after you learn the quirks and test which ways it can be used and abused. Designing it so that it loads the page instantly instead of waiting 3 or more seconds is great. It also didn’t take any more than an hour to complete. The only issue now, is that the viewer needs to have enabled JavaScript.

There are still ‘technically educated’ users that have JS disabled for popups, cookies, or some other half-baked excused that was only valid before Firefox. I mean, you would go to some porn sites back in the day and would have to disable JavaScript or you would spend 30 minutes exiting out of the popups.

I digress, I did create a Non-JavaScript page, but it still takes 3 seconds to load. I’m not going to do any optimizations for it. People without JS are going to be punished for their lack of enabling it or for not even using a browser that supports it. Only other user is for bots, which should look for the non JS version.

MVC

The main page is handled with Mod Rewrite and a single page to handle all of the pages. It lets me know what is finished and what still needs to be finished. The old version had sort of the same set up but all of the text was on the same page, so it made it somewhat difficult to find the parts. The new site splits the textual parts into their own files.

Possibly Related Posts:


Why Such Hate Towards PHP Patterns?

Put simply, of all the research sites I’ve ever gone to for information, this site ranks up there with some of the worse. It isn’t just the poor link color choice, it is the lack of organization. The articles, while outdated are well written and thought out.

I would rather have shelled out the money for a PHP book on the topic, which is always a good idea on complex subjects such as this. Programming Patterns have been around for a long time. However, they are usually targeted to a single language and it would be difficult for a novice who doesn’t know language of choice to convert it over to their own.

Patterns For PHP

Once this site is completed, I can see it having huge popularity and a valuable resource for PHP developers. The Popularity part should probably pick up towards the middle and then die to a manageable level. Hey, there are only so many patterns! It should be more popular than PHP Patterns once all of the Patterns are finished and it has a dedicated URL. I think patternsforphp.info would be a good URL, if it hasn’t already been taken. However, .com would be easier to remember.

However, I hope it becomes more like a living online OOP and Design Pattern Book. While the designs won’t change, there will be changes to the language and the examples will have to change. There won’t be much difference between PHP 5 and PHP 6 that the examples will have to be rewritten, but there are going to be some nice additions that could be placed on the site.

Patterns for OOP

I’m not sure what the overall plan for the site. I believe the owner stated that he would place some OOP related material on the site. I would be interested in formally learning the material, even if I have a OOP programming book on my shelve that I haven’t picked up for over a year. It isn’t six feet away.

If I wrote anything on OOP, it would be laced with references to other sites and books. Not a bad thing to have, so that if they wanted to learn more advanced topic they could buy the book (have a link to amazon) or go to the reference page for more details.

References

Technically, most of the articles on the page should have references to other pages and books where the material was first picked up. It would be difficult to go through and find all of the references that I read about months ago.

Writing SPL Articles

It is a reason why I haven’t wrote anything and don’t plan on writing any articles on other SPL iterators. SPL has a lot of Iterators and it would be nice to have all of it in one place, however, contribution should probably be made on the other SPL Wiki site instead. The style of the SPL Wiki is a good one, straight to the point with good examples. The question is, should I try to beat that? I’m not sure.

The issue is not that I can’t do it, the issue is that if I did, would I draw to much from SPL Wiki in that I’m just copying over material? Not intentionally of course. I just can’t justify writing something where there is a better source out there. SPL Wiki doesn’t cover all of the Iterators and SPL objects, but SPL has a lot.

Limited Contributions

I’m quite limited on what I can contribute to Patterns for PHP, I’m not familiar with a lot of Patterns listed and would have to do a lot of research and even then I’ll probably talk out my ass on some of the parts. I have written research papers, but they were on material I already knew something about. When I try to write about something I don’t fully grasp, it comes out vague and half-assed.

I’ll probably will do some research on the ones that the others are too busy to do to get them at least somewhat finished. The MVC Pattern will be of a Huge Interest to developers and for people wanting to use Zend Framework and others that use MVC.

Possibly Related Posts:


Patterns for PHP: Iterator

Patterns for PHP: Iterator has been added with some clearification and tightening.

Abstract

To get ready for when Patterns for PHP opens to the public, I want to start the draft for the Iterator Pattern. Mostly, because I’m quite horrible at writing about technical details and so that I can just copy and paste to the site.

I decided that it wasn’t worth going into detail about SPL FilterIterator and other SPL Iterators. There are already plenty of resources for which one can gather information. This will only touch upon the details of the Iterator Model separate of SPL, but also touch upon benefits of SPL Iterator.

Update 7/10/06

I think using the Stategy Pattern as a template would be better as I like how it is laid out instead. The Iterator Pattern is simple enough to match the earlier patterns, but I’ll be adding more details to it so that it won’t fit.

Introduction *Updated 7/10/06*

PHP has a history of using functions for iterating, but there is now a push to use objects in PHP 5. The Iterator pattern is not language specific and doesn’t need any language enhancements to create. The only added benefit however is the usage in foreach loops with the SPL Iterator interface, but more on that later.

The Iterator Pattern allows for accessing the current element and allowing the retrieval of additional elements in a loop routine or manually in a code block. The Iterator pattern is not constrain to the class for which holds the data. An object can also aggregate the iterator from outside its class providing iteration while also keeping from implementing the iterator as part of the object. Aggregation of the iterator is a better practice for optimizing overhead for developers who won’t use the main class for implementing the main Iterator methods.

The iteration in classes is not as simple as collecting all of the data and passing it off to the developer. This action doesn’t take in consideration the many data sources that could be used to gather the data in the first place. Including the initial iteration to collect and append the data to the array, which is not a optimal practice. With the Iterator pattern, you should only collect the information as you need it for when it needs to be passed to save memory.

The Iterator pattern allows you to control how the iteration operates. It makes the iteration go smoothly and easier for the developer as the method names are standard for each Iterator object and won’t need to reference a manual. A developer would be able to take any iteration and know that what method to call.

The SPL Iterator Interface

This Iterator interface used the SPL Iterator as a reference. All methods are public, therefore the implemented method must also be public even if not used [not tested, educated guess].

interface Iterator
{
    function key();

    function current();

    function next();

    function valid();

    function rewind();
}

Given the confusion with using key(), the number of iterations is often passed as the key. If you have pairs of values, it would also make sense to use the key method. It is not common practice to send the first element as the key and the rest as current. Data passed from key and current should be documented completely. The other method names shouldn’t be difficult to understand.

The SPL IteratorAggregate Interface

You should only pass the data that is needed to the Iterator, if the data is stored in the main class.

Iterator Aggregation allows you to develop without rewriting a lot of the same code for classes that need it. It is simple to implement with only one method in the interface.

It allows you to aggregate to PHP extensions that implement the Iterator pattern. If you need to pass XML, you can create a new SimpleXML class and pass it with the XML giving XML iteration without having to implement it yourself.

interface IteratorAggregate
{
    function getIterator();
}

The method getIterator must return an Iterator object.

Implementing An Array Iterator

The best way to learn iterators is to implement something simple, like array iteration. PHP SPL already supports array iteration using ArrayIterator and we will implement the functionality again, but ArrayIterator should be used for development.

class MyArrayIterator implements Iterator
{
    protected $dataStore = null;

    // Array hinting was added in 5.1.x,
    // in PHP 5.0.x, is_array($data) should be used
    public function __construct(array $data)
    {
        if(is_array($data)) { // For PHP 5.0.x
            $this->dataStore = $data;
        }
    }

    public function key()
    {
        return key($this->dataStore);
    }

    public function current()
    {
        return current($this->dataStore);
    }

    public function next()
    {
        return next($this->dataStore);
    }

    public function rewind()
    {
        return reset($this->dataStore);
    }

    public function valid()
    {
        // When Next passes over the end of the array,
        // current() should return false. Needs to be tested.
        return (bool) $this->current();
    }
}

The code keeps to the array parameters: if the array has a key, then the key is returned and all else is returned in current(). Reusing what PHP gives us, we can implement an Iterator for Arrays with very little overhead and speed reduction as compared to procedural.


$array = array('key1' => 'value1', 'key2' => 'value2');

Is the array which we will use to test the iterator.

foreach(new MyArrayIterator($array) as $current)
{
    echo $current, " ";
}

Will display: value1 value2.

foreach(new MyArrayIterator($array) as $key => $current)
{
    echo $key, " ", $current, "\n";
}

Will display:

key1 value1
key2 value2

Implementing a MySQL Iterator

A once hot topic was using an object to iterate over Mysql rows, however since the addition of PDO, it has ceased in relevence. The method for which to control iteration is to either pass SQL to the iterator or to pass the mysql_query() resource to the iterator. The Iterator object should handle both. The iterator should only control how the data is passed and not how it is received without good reason. It is not difficult to check to test the input into the constructor.

class MysqlIterator implements Iterator
{
    protected $row = null;
    protected $query = null;

    public function __construct($query)
    {
        if(is_string($query)) {
            $this->query = mysql_query($query);
        } else if(is_resource($query)) {
            $this->query = $query;
        }
    }

    public function key() { } // Not Implemented

    public function current()
    {
        if($this->row != null)
        {
            return $this->row;
        }
    }

    public function next()
    {
        $this->row = mysql_fetch_assoc($this->query);
        return $this->row;
    }

    public function rewind()
    {
        $this->row = mysql_data_seek($this->query, 0);
        return $this->row;
    }

    public function valid()
    {
        if($this->row == false) {
            return false;
        }

        return true;
    }
}

Saving the internal data for only storing the current row array. Rewinding will seek to the first row. The optimizations should be quick enough for common use.

Iterator Pattern In Loop Constructs

The Iterator objects are not limited to foreach loops and can be used in other loops. Foreach is common practice, because only the class is required and the other loops need manual work.

To use the Iterator pattern in a while loop, you can make the code look beautiful while not changing anything.

$iterator = new MyArrayIterator();

$iterator->rewind();
while($iterator->valid())
{
    $data = $iterator->current();

    $iterator->next();
}

You could even use the for loop method to put all of the pieces together, which would make more sense for PHP 4.

$iterator = new MysqlIterator();

for($iterator->rewind(); $iterator->valid(); $iterator->next())
{
    $data = $iterator->current();
}

Disadvantages

Iterators don’t save you from poor implementations of the interface methods and poor optimizations. You can bring a script to a halt or add not only a few milliseconds, but a few tenths of a second. Using the Iterator Pattern will decrease the speed of the script over the procedural method, but if done right it should be managable and predictable time decrease.

Not all of the SPL Iterators are in the PHP 5.0, the main classes which are discussed here are. For most tasks, you only ever will use Iterator and IteratorAggregate.

Conclusion

The Iterator Pattern is not a replacement for SQL, filtering and limiting should be done at the database. Separation of the iteration and main class functionality adds to the code reuse and speed for which projects can be developed. They are an useful tool for managing data and controlling how a developer has access.

One of the greatest benefits of SPL is its many Iterator Pattern implementations. Most of the SPL is at the C code level, so you can almost count on its speed. The code that is still in PHP will be moved to C, so the later the version the greater the chance that it is at C level. You don’t have to depend on SPL Iterator and IteratorAggregate and can easily port it to PHP 4, but you’ll have to use either the while or for loops instead.

SPL Resources

SPL Wiki – is an excellent resource for quite a few of the SPL interfaces and objects.

Possibly Related Posts:


Zend Framework Critique

First Impressions

Loved the Filter and InputFilter, but then I realized that some parts weren’t finished and I told myself that I don’t have time for this crap. The code was several levels above my own, because I had no idea on how to use some of the components.

The first two I mentioned were easy enough to understand, but everything else fell into the category of ‘not going to be used’ or ‘interesting if I knew what the code meant’.

To spend a few weeks learning the framework and making it my own or create my own implementation that I would understand and actually probably use. I choose the latter, which I don’t regret, but the former would have been a far better usage of time.

Oh, Sweet Irony

I became curious on the progress made so far, so I took a look at it recently. To my surprise I found configuration classes that matched my development some time back.

Well, I had planned for the classes, but never finished the XML or INI one. I believe I will take a look at the classes later and once I am approved, I look forward to submitting patches for it.

I think I might give my database one. I would have to seriously change it to match the other classes. It would be interesting to see if anyone accepts it.

Yadis and Zend Framework

The Zend Framework has HTTP client classes that match the ones in the other Yadis Libraries. It wouldn’t be difficult to create a service and add it to the Zend Framework. However, I would have to write a proposal, which would have to be critique and then accepted.

I am currently using the Zend Framework to develop the Yadis Service. Going through the HTTP classes and the URI classes has kind of left me in thought shock. It is a lot to think over and I’ll probably have to create a few tests with the HTTP classes and see the interaction between the HTTP and URI classes to create the Yadis Service.

Bugs?

The biggest issue is whether or not there are bugs in the framework that I will have to immediately fix. I want the HTTP classes to just work and focus my attention on the Yadis Service.

I could give a patch of the bug fix, but it would have to be over the Mailing List until I sign the license and send it in.

Even if there aren’t any bugs, it is still my fear that I’ll probably run into them later.

Incomplete Components

I don’t like that some parts of the InputFilter and Filter are missing. I don’t feel like spending the time to implement the missing part and then have the code replaced later by another’s code.

What I’m saying is that I can justify spending (or wasting) time implementing my own wheel over fixing the wheel that already exists.

It will be hard to change, but from all of my reading, I would save a great deal of time using the Zend Framework, instead of creating my own wheel each time.

Browser Game Engine Using Zend Framework

Not yet, but I believe a time will come when I finish all of my other projects when I will consider it. After all, if I start using it now, then it won’t be a new thing that I have to learn when I start using it for the browser game.

The learning curve will be raised for the other developers that wish to work with it. However, it should be up to me to make it so that the others can implement features and mods as easily as possible.

That can be done built upon a layer of already created, tested, and tried Framework.

Ez Components?

I am not ready yet for Ez Components.

I am going to follow Ez development and see if any components interest me. If there comes a object based template system that replaces Smarty, then I’ll be completely up for it. I may even make it myself, but if I do, it will be proposed for the Zend Framework.

Once I master the Zend Framework, any others shouldn’t as difficult as they would be right now.

Possibly Related Posts:


Behind Yadis

Keeping it Simple, isn’t always simple.

I’ve been doing some tests on sending and receiving XML using a HTTP method. Doing so, I’m starting to learn how difficult creating the technology and how much work went behind Yadis.

You can’t just create a standard half assed and expect people to use it. The tests don’t use this principle currently, but they will, I’m writing my standard as go kind of thing and will release a final version when the tests have concluded.

The API for Yadis is very easy and simple to use. The same isn’t true for the backend. The backend is hell, unless you are a l33t master.

Case In Point

PHP DOM says that using the loadHTML() function won’t validate the data, it does. In retrospect, I probably should have tried setting validateOnParse to false. I thought the default was already false. Have to do some research in that.

Using the DOM method to get the Meta data would be far better method than using regex, however DOM was meant for XML and some HTML doesn’t conform well to standards. It will ‘work’ for browsers, but DOM class is going to say, “This HTML is not well formed. BOOM!” Not good when you absolutely have to correctly get the meta tag every time.

Redirection

One of the nice things that I thought was neat about the standard is that if you don’t have PHP support, you can still benefit from Yadis. Yadis standard supports redirection and will redirect until it gets to the Yadis document. Therefore, if you are a cheap server that doesn’t give you PHP/Mysql support, you can set the meta tag to a server that supports yadis. However, I fail to see the use of linking to a server that doesn’t support PHP, you should just link to the server that does support Yadis.

It is more for when you don’t want to link directly to the Yadis document. It is easier to change the meta tag when you change servers than to update the sites that you linked directly to the document. The standard smartly allows linking to the server, but it is has more to do with OpenID already supporting that feature.

It make senses and makes the standard extremely strong.

Yadis Flaws

  1. Requires Yadis Content Type

I haven’t filed this suggestion to the main standard developers. I have been planning to do so, but I don’t think it is much of an issue currently.

In my implementation, if you say the content type is just ‘text/xml’, then awesome, I’ll still parse it. Hell, I’ll do one more and try to parse the XML as long as it conforms to the standard. I’m just that nice of a guy!

Actually, I think they just did that to add in a protection for parsing. You should check to see if the element exists before using it anyway, so the point is mute. If they wanted people to that, they should also call for a new extension for the file that holds the data. The Yadis Library authors may already do this, but I suspect that many don’t since it is part of the standard.

It is hard to set the content-type unless you use a programming language to set the header for it. The XML parsers may also check the XML for the content-type, instead of the Header information.

  1. API: No Iterator

In my implementation, I’m going to use the PHP 5 Iterator support for getting the services and I’m also going to allow searching for a search (think it is part of the Yadis API in the hasService method, but it has been a few days since I’ve looked at that part). The PHP 4 classes can be used in a while loop however, but I’ll rather use foreach thank you.

All of the implementations that I could find are written for PHP 4 with PHP 5 support. Okay, that allows me to give PHP 4 the finger and develop using all of the PHP 5 features. If someone wants PHP 4, they can use the other libraries.

Possibly Related Posts:


Why I don’t use EZ Components or the Zend Framework

1. Licenses

I don’t want to be restricted to their licenses and I want to be able to sell the project if at all possible. I haven’t even decided what license I’m going to use for the game engine project. I may use the projects as research as it is worked on by some very intelligent people and coding by example is how I learned up to this point anyway. The only issue is that I can’t use any of the code in the frameworks or I’ll still be subject to their license. Which is why I’ve been hesitant up to this point to look too far into how they do things.

2. Bloat

I don’t need all of what the frameworks offer. Also, I would have to find out if I could package the frameworks with my game engine, but most likely would depend on them to download the separate packages themselves and copying only what they need. Some may get it, many others would not and I would lose them to another game engine.

3. Class Design

Some of the techniques are difficult for me to understand, so even through I’m using classes and limiting the developers that would want to work on or with the code, using MVC or class designs other than a Factory seems to be far to difficult to force onto other developers. Developers may have some class experience but would otherwise shy away from a project that depended on developing multiple different classes to even do a simple task.

4. Learning Experience

I want to see if I can do certain things myself to gain the perspective in what it takes to develop the different technologies. If I just use another’s technology, then I can understand how to use theirs and learn it well, but I’ll never learn how they developed it. I would be completely dependable on what they code and how they code it. If I wanted something else, I would either have to go to another framework, or try to add it myself. I would learn from editing the framework that I’m using, but it would take longer.

I have been able to develop two different factory based classes without any documentation or help and had it work with a small amount of bugs.

Why I should use the developed Frameworks

I would be using something that has been tested, developed, and maintained by a group of experienced talented programmers with years of programming far beyond my own. I’m only self taught working on PHP and classes for a few years compared to those who have been programming PHP and other languages for more than a decade. I’m not saying I’m better than them, just that I want to learn and solve my own problems for the moment.

I do use SPL, which could be considered a framework, but a lot of it is built into the language and offers many different features that would be impossible any other way. Since it is built into the language, I don’t have to depend on the other developers to download a separate package, just require the version of PHP 5 or 6. However, SPL is somewhat faster since it is part of the language.

The issue is also that everyone is developing the same wheel over and over again and not using what someone else started or developed. If you look at the number of forums out there, you will find a large number of various features and stablity. You will find that one forum usually offers a feature not in another but also lacks a key feature found in another project. If either one of the developers took the time to combine projects and work towards the same goal, then they could both have the same features and work on only one forum. The same could be applied to the number of game engines. That compared to the online games that actually make a profit and have a large (100,000+) active userbase.

Possibly Related Posts:


Simple Code base vs. Complex Code Base

After reading the Dragon Knight forums for quite a while, I have come to appreciate the simple, clean coding that is Dragon Knight. What other complete script allows any beginner coder to hack away at its code base? Not phpBB, hell that is far beyond my comprehension let alone modification skill. On some level, WordPress is in the middle and heading in that direction.

I think that is the problem, the more features and an web application evolves the harder it is for lower level coders to start working on it. With all of the beginner coders that I seen (not the ones who bitched about simple errors and problems) take the code and take it far from what it originally was, it really sticks it to me.

I always thought that features and advanced coding made an web application great and popular. The problem with a game engine is that not everyone needs or wants to have a online game on their web site or sees a need for it. I think that some may want to have it but think it would be too difficult. Even if they find Dragon Knight or some other Online game engine, they want it to be something it is not and don’t want to mod it, either because they don’t know how or don’t want to find the time.

Rewriting the Dragon Knight code to be PHP 5 is not going to allow beginners to easily access and modify the game engine. If the coding is too difficult then it would have to have a lot of features towards changing the game functions and how it works. Making any game special and unique takes a great deal of work from the creator, the game engine is just a tool towards making the goal that much closer.

I still remember when I first went to the Dragon Knight forum and stated that the Dragon Knight code was crap. I believe I forgot to mention that I had only a year and a half of off and on programming skillz and had only full developed a guestbook, simple message board, and unsecure personal site. I also made my own game, which was also god awful. The backlash was terrible indeed.

Possibly Related Posts:


SQLite and classes

While working on the Sign In class, I realized that I have no idea how I’m going to work it. After creating the first class of which I tested the theory of my creation, I thought that if I kept adding functions to the class that it would eventually become as the old classes that I made in the game that failed because it couldn’t be extended any further. I do understand that there is no way, as of now, that I will be able to keep it all at one class which in turns has some automatic controls below it.

After I started to write about how I was going to do it, the idea came to me and I figured it out and I finished it with it being an awesome improvement over the old one I made last year. There are still a few changes I may make but right now I think it is all good.

Possibly Related Posts: