Posts Tagged ‘php’

Uganda Web Developer Workshops: Rotary Style – Idea looking for Partners and Direction

This is an idea that has been growing in my mind, and I seem to finally have a handle on it. I have been a professional PHP web developer for the last 12 years, and have gone through the learning and transition cycles from learning a new language from Visual Basic 6 and MS Access to Java/JSP/Servlets to PHP, and developing in the language from direct database access using mysql_query through a custom developed database class into Zend Framework for 2 years with Doctrine 1 and 2 ORMs.

My biggest challenge has to do with the fact that there are no places to go and talk code, PHP/Javascript/Database in Uganda, along with the experiences and challenges facing web development with “need-to-have” practices like:

  1. Refactoring
  2. MVC design for web applications
  3. Version control – branching, merging, version tagging and management
  4. Testing – unit and functional testing, load testing
  5. API development (okay this is pushing the enveloper)
  6. Continuous integration, code quality metrics – complexity, modular development, cyclomatic complexity
  7. Team Style development – PSR 0 and PSR 1 compatibility
  8. Frameworks – Symfony, Zend Framework, Kohana, JQuery, Twitter Bootstrap
  9. Advanced CSS and HTML 5 – style guides, browser targetting, mobile development

I am also looking at doing this Rotary style, 1 hour developer meetings once in 2 weeks, then later once a week, same night, same location.

The bottom line is that we develop the quality of the available pool of web developers by growing a community, having role models, to also put a brighter face on the industry, improve perceptions and make it clear that this is an area that has professional practices. It is a win-win for all involved

Any ideas who has done this before, what were your challenges and trials, who would like to partner on this?

The Poor Man’s Job Queue

Not all software development projects are treated the same, some have access to modern tech Virtual Private Servers (VPS), Zend Server (http://www.zend.com/products/server/), Memcached, Gearman and all the other goodies I can only dream of. You have a box with LAMP, and you cannot install anything else.

This is an example of how we got around a limitation, using available tools. Problem: I have a list of tasks to execute within my application, however I need to ensure that the tasks are executed and completed, but some are more important than others, and the execution may slow down the performance of the box we are running on. Well in this case we were loading 6 different types of XML files which were FTPed into a location on the box regularly, every 35 minutes and had to be loaded in a specific order. This was further complicated by the fact that we had to reload historical data in case of issues (1 weeks worth of uploads ~ 2100 files) without interrupting the current loading processes.

The approach used the following components:

a) Job Queue – based on the Zend Server Job Queue but simplified for our needs (see data model of tables below)

Job Queue Data Model

Job Queue Data Model

b) Queue Loader Script – loads the jobs into the job queue by scanning the location containing the files to be loaded and adds the files to the queue (since the queue is a database table, duplicates are discarded without errors) This keeps this file simple and honest

c) Job Executor Script – reads a message from a queue, reads the message body which contains the file name to be processed, could be made more complex

d) Queue Loader Cron Job – calls the Queue Loader Script to add new files to the queue

e) Job Executor Cron Job – calls the job executor script. This job has no effect if a lock file exists, and is not expired which means the script is valid and running. However if the lock file is expired, it means that the process crashed, so the lock file is deleted, a new process is started with a lock file. Basically this keeps the job executor script running indefinitely as long as there are messages to process. 

Please feel free to leave a comment on what your experiences are with similar problems. 

Doctrine2 Day 3 – Proxies, Associations, Relationships

Well if you are following this series, then by know you are aware that we have the validators setup, and we are almost ready to go. Well not quite so. I ran into an issue with proxies and class loaders which took a while to resolve, but what I did was:

a) Changed the Zend Framework-Doctrine2 integration to the Bisna integration (https://github.com/guilhermeblanco/ZendFramework1-Doctrine2) – note the additional configurations before

b) Learnt that DO NOT SAVE ANY MODELS IN SESSION OR CACHES due to Proxy auto loading issues

c) Develop unit tests for the model validations and saving as you go along because they will save you as you shift things around . I am currently trying to save an association to the database but due to the tests that I have running I can test out the different association mappings without issues because I track the changes using my unit tests.

Now onto relationships, well what I found was a follows:

  1. I have been having a tough time dealing with relationships from Doctrine 1 which autoloaded relationships, however with with the Doctrine2 data mapper, you have to auto load the associations your self
  2. In Doctrine 2, you cannot define the foreign key column and relationship as this creates problems for the ORM mapper, so since I need to access the foreign key value for example personid, and the related object person, my approach has been as follows:
    • Added a person instance and relationship mapping to the person as per the Doctrine
    • Add a setter setPersonID() which loads the Person from the database using the provided ID and sets it to the person relationship provided
    • Added a getter getPersonID() which obtains the id of the person for use on the screen
  3. As recommended avoid bi-directional relationships where possible, try to keep them as uni-directional as possible.

Next I will be implementing a nested hierarchical structure using the tree nested set implementation at http://www.gediminasm.org/

Doctrine 2 – Day 2 – Model Validation using Symfony Validator Service in Zend Framework

It is just Day 2 of my experiences in the trenches, regular work, had kept me from this but I managed to get some time to keep digging. As a followup to my Doctrine 2 – Day 1 – Commentary from the Trenches. The models are up and configured, and the unit testing is setup following steps from Michelangelo van Dam’s presentation (http://www.slideshare.net/DragonBe/unit-testing-zend-framework-apps).

One of the major process that we are implementing with this migration is detailed unit testing which was tougher with the Doctrine1. With the unit test infrastructure setup, the next item on the agenda is model validation. From previous experience (before Doctrine 1) and with Doctrine1 it is critical to be able to specify validation rules using annotations without having to write PHP if statements. Being a ZF person, the first step to look was the ZF validator classes. While they seem to be well integrated with the forms, they would prove to be too verbose to use for validation of models, since I also need to be able to specify multiple validators per column, and this would not cut it for me.

Next stop was Symfony2 validator service (http://symfony.com/doc/current/book/validation.html) provides validators with annotations support. So that was the easy part, the hard part was yet to come integration. The integration followed the steps below:

a) Add Symfony Validator service to library folder, easy, just download a package from https://github.com/symfony/Validator

b) Register the Symfony Validator annotations – this is where I had problems (more later)

c) Add the Symfony Validators to the model properties

d) Add validation code which needed a validate() method in the base class from which all entities are derived, which requires @ORM\HasLifecycleCallbacks (so that the model can hook into the lifecyle call back models) @ORMPrePersist and @ORM\PreUpdate for the validate method to ensure its called before the models are saved (first time) or updated. More details on the Doctrine annotations can be found at http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html

So what problems did I face.

1. From the Doctrine documentation, you use the annotations directly, for example @Id, however experience has shown that you need to namespace and alias them see note from Symfony integration http://symfony.com/doc/current/book/doctrine.html . So I had to change all the Doctrine annotations to use @ORM namespace

2. The default annotation driver only supports a single namespace so you will need to update as per the pastebin below

http://pastebin.com/embed_iframe.php?i=feiKsVxg

Now I am a happy camper, got my models working using Symfony validations, we only have to write code for custom validations which happens only about 20 – 30% of the time.

As a parting shot, the Symfony team and community have done a great job for PHP, why because they provide standalone components (similar to Zend Framework), but each of their components can be used without the rest of the framework. As I was investigating the validator usage and issues, I found a thread where Fabien Potencier and team were discussing annotation support in Symfony. However they also noted that Doctrine Commons had better support, so they stopped the work on Symfony annotation support and just used the services of the Doctrine team. This is how all software development should be done, and is a torch to the rest of us. I am a convert, and happy to be a proud member of the PHP community.

Update May 8, 2012

I had promised to provide some sample snippets of what I am using for the integration with Bisna integration and Symfony validation that I ended up using so here we go https://gist.github.com/2638526 The files are as follows:

a) application.ini – there is nothing special here from Bisna. Includes the cache configuration, prod/staging/dev/test environments all of which inherit from production

b) index.php – from the public folder or htdocs – this may not be perfect but it works and am looking for ways to simplify it

c) Bootstrap – this is the file we use, highlight:

– Storing the entity manager instance in the Zend_Registry, we have a utility method which loads it from the registry and another which also provides a connection from the entity manager so its fully encapsulated

– intialization of the Zend_DB adapter, we need this since we are using the Zend_Session to save the sessions in the database

– the last config is for other resources we use. We have a dependency on the Zend_Registry class as it hides a lot of complexity

d) Document.php – a sample model class

– it extends BaseEntity which provides automatic getters and setters through the __call method, some required fields like id, datecreated, last  update date and last updated by (not all models extend this class only those which need those auditing fields)

– Why do we have getCategoryID(), setCategoryID() for the category property instead of mapping the categoryid field from the database see the next post in the series https://ssmusoke.wordpress.com/2012/03/25/doctrine2-day-3-proxies-associations-relationships/

– Unlike the Doctrine2 defaults we do not use tablename_id but rather tablenameid for the foreign keys so we have define them in each relationship.

Please let me know what I can do to make this any clearer, thanks for reading

State of PHP Feb 2012 – Symfony 2, Zend Framework 2, IDE Support, MySQL

There is just too much going on so I thought I should put these thoughts down so that I do not lose my mind from the excitement and anticipation that comes from things moving very fast and innovation being spured at a pace which is mind boggling.

PHP

In my opinion the stabilization of PHP 5.3 which introduced namespaces (similar to Java Packages) was the first shot across the bow, and I expect 5.4 with traits to bring even more reusability. However our hosting providers are slow to upgrade most are still running PHP 5.2, without general availability for 5.3 just starting to appear

Frameworks

There are two main frameworks in the bull pen Symfony 2 (http://symfony.com/) and Zend Framework 2 (http://zendframework.com/) currently in beta. However they are as different as can be. While Symfony 2 has been refactored from a full blown framework to a bunch of core reusable components, its moving towards ZF2, in that its not trying to be all MVC, forms etc, but is rather a set of building blocks to provide web application framework. So good is it that Fabien Potencier the lead developer has a series on how to build your own framework on top of Symfony at http://bit.ly/zVLi7X

ZF2 on the other hand is a bunch of reusable components which you can mix and match with other frameworks which also provides an MVC, ORM etc.

If you have been in the Java world, Symfony is more like Spring Source () while Zend Framework is Apache Jakarta (http://jakarta.apache.org/)

Interesting tweet that sums it all up:
Every time a developer complains about php, the #Symfony2 community creates another great, namespaced, decoupled and reusable component

IDE Support

Zend Studio 9 was let loose at ZendCon, Oracle released Netbeans 7 (which supports ZF1, and Symfony), Eclipse PDT is chugging along, PHP Storm from Jetbrains creating  a storm with others  Vim, Notepad++, Sublime Text basically all you need to do is pick your poison.

Communities

Github (http://www.github.com) is the new Facebook and LinkedIn for developers, where all the action is happening for all the major PHP communities, you had better be there. Forking and making changes is as easy as a button press. I am yet to push my first commit to a project but I am getting there.

MySQL

The best know web database is getting losta love from Oracle, and also the community led by Percona, SkySQL, Monty DB, and many others. Where it seemed lost with lost of FUD during the $1bn Sun takeover by Oracle, it seems to just be gaining steam (at least from my viewpoint as a consumer, developer and user). Now at 5.5, with 5.6 starting to appear over the horizon …

While there is a barrage of NoSQL solutions, Hadoop leading the charge, MySQL provides a NoSQL interface via HandlerSocket (https://github.com/ahiguti/HandlerSocket-Plugin-for-MySQL) and MySQL Cluster (http://www.mysql.com/products/cluster/)

Supporting Infrastructure

This is where all the fun happens, who is using the language and what are the trends. Here is a snapshot:

  1. Content Management Systems – WordPress is getting lots of love, while Joomla now at 2.5 supports databases other than MySQL. Drupal is adopting Symfony 2 as its core framework while Magento runs off a modified ZF1 kernel, while XOOPS (http://xoops.org) is being rewritten to use ZF1 or two
  2. Template Engines – an area where battles are found won, and lost. Smarty now at 3.0 (www.smarty.net), has to battle Twig (http://twig.sensiolabs.org)  which is surging due to its usage in Symfony 2
  3. Web services – JSON, XML, AjaX, Rest Interfaces are no longer buzz words they are the norm with native support being baked into PHP
  4. Object Relational Mappers (ORMS) are one of the core developer architectural choices, in PHP we have ZF Table (Table Gateway), Doctrine 1 (Active Record), Doctrine 2 (Data Mapper), Propel (not used) in addition to plain old PDO all of which provide rich choices. Interesting is that Doctrine 2 provides an mapping for MongoDB which shows its versatility similar to Hibernate for Java
  5. Continuous Integration – with Hudson and Jenkins, and now Travis which is also hooked into Github provides a great way to continuously monitor the quality of your development
  6. Quality Control – PHP Unit has always been there but now we have mess detectors, and other metrics (do not make sense of them yet), but whatever you want to measure there is probably a tool for it.
  7. UI Toolkits – JQuery took the world by storm with JQuery UI providing a set of theme-able components, but we have HTML5 boiler plate and Twitter Bootstrap which are simplifying the cross browser issues we developers face.
  8. Performance – always a PHP problem but it has improved through 5.3 to 5.4, and other techniques like OP Caches are becoming more maintream, Memcache is pre-built into Apache …

Exciting times to be a PHP web developer oopsss we are not web developers we are Software Mechanics (http://www.brandonsavage.net/the-mechanics-of-code/)

Doctrine2 – Day 1 – Commentary from the Trenches

The new year is here so it is time to get cracking on infrastructure for the year’s development projects. There are a number of things we have been putting off, but now that a number of our client hosts support PHP 5.3, it is the right time to move up the stack for our ORM from Doctrine 1.2 to Doctrine 2 (which feels more like Hibernate) than anything else.

Well step 1 was downloading it, I went straight to Github (https://github.com/doctrine) , got the Doctrine-ORM unpacked it dropped it into the library/Doctrine and was chugging away when I got errors. Seems like some classes were missing …

Tip #1: Download the ORM or DBAL packages from the main project website and you will get all required classes

Anyway classes in tow, I started cutting away at the Doctrine 1 classes to remove all that is not supported it is alot. Doctrine 1 was an Active Record implementation (http://en.wikipedia.org/wiki/Active_record) which meant that you had to extend a base class Doctrine_Record, while Doctrine 2 is a data mapper (http://martinfowler.com/eaaCatalog/dataMapper.html), you write POPOs (Plain Old PHP Objects) for which you provide the mapping metadata so the database access is handled by a service layer.

We chose to use PHP Annotations over YAML and XML so that we do not introduce any dependencies and maintain the mapping metadata within the model classes.

Next step was integration with Zend Framework, so I followed the instructions at the Mayflower Blog (http://blog.mayflower.de/archives/799-06.12.-Doctrine-2-Zend-Framework-Integration.html)  with the following tweaks:

  1. Application.ini – instead of using doctrine.connectionParameters maintained the resources.db.params configuration which we use for storing sessions in the database using Zend_Session
  2. Bootstrap – load the resources.db settings and change configurations user to username and adapter to driver which Doctrine2 expects.
  3. Change production caching to ArrayCache since the shared hosts do not usually support APC, this will change on a project to project basis.

At least now the pages load now into the model configurations. We use two base classes BaseRecord was the one which extends Doctrine_Record in 1.2, and BaseEntity which provides commonly used properties id (autoincrement), datecreated, created by, lastupdate date and last updated by columns which are common to all tables.

First step was to add the mapping annotations, the column definitions are similar to Doctrine 1 with sensible defaults, which helps. However the associations were a mean piece of code, since the Doctrine 2 conventions are a total mismatch to normal database terminologies which I was used to. Opened a github issue too at https://github.com/doctrine/orm-documentation/issues/80 (my first Github and Open Source issue)

Anyway what is interesting in the association mapping is that the mapping columns are defined in the annotation and private variables are not defined for the mapping columns (at least I do not see that in the examples) may come back to bite me later when I start saving the entities, but that is for another time

So anyway classes setup, now the next problem I ran into. In Doctrine 1, the Doctrine_Record provided two methods:

  1. Merge – which merges data into the object
  2. SynchronizeWithArray – same as merge, but had an added function, if you have relations defined and do not pass information in them, then the relations are removed, which was excellent for cases where you need to remove relations in a hurry

Where does this leave me now, action items are:

  1. Setup automated binding of an array of data to the object, and how to deal with relations …
  2. Update the application code to enable an object to load its details from the database … seems crude I will look at what others do
  3. Add Validators since Doctrine2 provides none. Now I need to poke into how I can use Zend_Validators without too much overhead and new changes for my team …

Anha one last one, I wanted to have a PDF of the documentation, since I wanted to use it on my PC faster than opening pages, but none was available. I pinged Jonathan Wage (http://www.jwage.com/) and he pointed me to Read the Docs ( http://readthedocs.org/) which generates documentation for projects from Github etc, so you should check it out. Anyway I searched for Doctrine ORM documentation, downloaded a PDF and now I am in business.

All in a day’s work, and I hope to keep plodding and poking into it as promised.

My take on Day 1, the models feel light weight and more like POJOs, well I think PHP is becoming more and more enterprise ready as it supports core patterns of Enterprise Architecture a Martin Fowler religion that I subscribe to …

Till next time

Joomla Tip – Custom Content Integration with Jumi

Just wanted to share a Joomla (1.7) tip on how we were able to integrate custom content from an external web application with custom PHP code via the Jumi component and plugin (http://bit.ly/wWIQmz).

Joomla by default does not allow custom PHP code to be added to articles (content pages) functionality which is provided by the Jumi component. However in our case we also wanted to display the most recent report on the home page, plus the last 10 from the archives when the user asks to view more.

  1. Create custom PHP files to load the current report and one for the archives. These were placed in the Jumi component files folder. TIP Always include the PHP line  defined('_JEXEC') OR defined('_VALID_MOS') OR die( "Direct Access Is Not Allowed" ); at the top of the file to ensure that it cannot be loaded directly via HTTP.
  2. Create Joolma article with a Jumi plugin to load content from the external url. We used two calls to the url, the first one to load the latest report and executive summary and the second to load the archives.
  3. Use the excellent Gavick News Show Pro GK4 (http://tools.gavick.com/newshowpro.html) to load the article into a module position. However since we can limit the text brought back, we limited the text only to the first plugin call to load the latest report only. This will include a more link to display the current report and archives.

NOTES:

  1. When loading external urls we used the Curl Library (inbuilt in most PHP installations) since file_get_contents() is usually blocked from accessing external urls
  2. We could not use an external library as it seem like Jumi does not handle include paths very well, so we could not maintain configurations in an external file.
  3. When deploying into production, we had to set caching on otherwise the page loading took too long

Hope this helps you

%d bloggers like this: