2011年8月31日星期三

Community News: Latest Releases from PHPClasses.org

Chris Jones' Blog: PHP 5.3.8 RPMs are on oss.oracle.com


Chris Jones has posted a quick note to his blog today about some new PHP packages that are available from Oracle of 5.3.8 (RPM) with one of the latest OCI8 extensions already included.



I've built PHP 5.3.8 RPM packages with various common extensions (and the latest OCI8 1.4.6) for Linux x64. They are downloadable at oss.oracle.com/projects/php/. These binaries might be useful for quick testing. They are unsupported.


He points to packages on the ULN site if you're looking for something a bit more stable. The OCI 1.4.6 version of the extension includes a few new features but was mostly a test suite update.

Liip Blog: 2-Step Verification with Google Authenticator and PHP


On the Liip blog there's a recent post talking about a tool Google offers to help you authenticate your users, a one-time passcode generator called Google Authenticator. The post talks about a PHP port of the same idea.



The main point about 2-step verification is that something else than your computer provides that token. If it's on your computer and that one gets stolen (or hacked into), it won't help much for the additional security. That's why you need a second device for those tokens. Some banks do that with SMS/Text Messages (Facebook, too), other give you special devices for that (eg. RSA keys) and the last group does it with your smartphone.


At the request of a client, they created a tool that did just this, but for PHP. As a result, they created the GoogleAuthenticator library that makes it easy to implement in your application. There's even an example of it in use. For more information about the Google Authenticator tool, see this page on Google Code.

Tutorialzine.com: AJAX-enabled Sticky Notes With PHP & jQuery


On the Tutorialzine.com site there's an interesting (though a bit older) tutorial showing you how to combine jQuery, PHP and some CSS+HTML to make a simple sticky note application complete with multiple note support and drag-and-drop abilities.



Today we are making an AJAX-enabled Sticky Note management system. It will give visitors the ability to create notes with a live preview, and move them around on the screen. Every movement is going to be sent to the back-end via AJAX and saved in the database.


They use the fancybox plugin for jQuery to make creating the notes a lot simpler. Included in the tutorial is all of the HTML, CSS, javascript and PHP you'll need to create the application (as well as plenty of description along the way). You can see a demo of it in action here or just download the source and dive right in.

2011年8月30日星期二

Community News: Latest PECL Releases for 08.30.2011

Latest PECL Releases:

Lorna Mitchell' Blog: PHP OAuth Provider: Access Tokens


Lorna Mitchell has posted the latest in her look at OAuth in PHP to her blog today, an introduction to access tokens - generating and handling them in your application.



I've been working with OAuth, as a provider and consumer, and there isn't a lot of documentation around it for PHP at the moment so I thought I'd share my experience in this series of articles. [...] This entry follows on from the ones about the initial requirements, how to how to handle request tokens, and authenticating users.


In this latest post, she talks about the three different types of tokens - consumer, request and verififier - and how to use them to locate a user in your app's users. Her code validates the request token and verifier against the database and, if successful, inserts the rest of the token information for the user.

Alessandro Nadalin's Blog: Behaviour what?


In a recent post to his blog Alessandro Nadalin looks at a different approach to development than the usual code-first, ask questions later style, behavior-driven development, and a tool that can help you follow this method - Behat.



Although this requirement is not mandatory, BDD's power is leveraged by using stories. It basically assumes that instead of focusing on tests, we should start our development process writing down a story that a parser can translate into a test (a customer cares about features, not tests) a programmer can implement in order to verify that our software respects that story.


He talks about installing Behat via PEAR, how it can integrate with Symfony (1.4) and an example of a sample story/test file that checks a few things against a basic page. He also points out an interesting and quite useful feature of Behat - outputting the tests in a HTML-formatted result that makes for easy reading by non-developers.

VXTIndia Blog: How to setup your new VPS Ubuntu server


On the VXTIndia blog there's a recent post that gives you a very complete guide to setting up a VPS server running Ubunut with all of the software you'd need to get a (more than) complete server up and running.



Every time you purchase a new Linux VPS, you need to go ahead and set it up for use. Even though we manage to do one server a month, we always seem to forget one thing or the other. So we decided to write down the things that we do. I thought it would be a good thing to share it with everybody as well, so that we could get a few comments about what we're doing wrong, and people who do it the first time can probably pick up a few things from here.

Steps and software involved in their process include:



  • Updating to the latest Ubuntu packages
  • Creating other users for the system
  • Installing the web environment (including PHP, MySQL, phpmyadmin and Apache2)
  • Minin for monitoring
  • Configuring IPTables
  • Installing Fail2Ban


All of this comes complete with the additions you'll need to make to configuration files and the commands to get everything installed (via aptitude).

2011年8月29日星期一

Community News: Latest PEAR Releases for 08.29.2011

Latest PEAR Releases:

Phil Sturgeon's Blog: CICON2011 and the future of CodeIgniter


As mentioned by CodeIgniter.com Phil Sturegon has posted a wrapup of this year's CICON2011 (CodeIgniter conference, US-side) that happened in New York on the 20th.



CICON2011 happened and it was awesome. We had 100 CodeIgniter nerds in the same place - which is the biggest collection of CI nerds since 54 at CICON2010 in the UK, but this event was so much better. We had a whole load of announcements that have changed the way the framework is contributed to and improved the whole community for the better. This is not me blowing smoke up my backside, but feedback I have had from attendees. So, what did you miss?


Some of the things on his list have already been announced through other channels, but it's good to have them all in one spot:



  • The move of the project to Github
  • the merging of CodeIgniter Core and Reactor
  • The merge of the Sparks library functionality into the core
  • as well as some general positivity in the community


He's also linked to a few other summaries of other folks that were in attendance: Adam Fairholm, Frank Michel and Greg Aker.

Michelangelo van Dam's Blog: Quality Assurance on PHP projects - PHPUnit part 3


Michelangelo van Dam is back today with the next part of his "Quality Assurance in PHP Projects" series, the third part of his look at PHPUnit, the popular PHP-based unit testing software.



Time for the third part on unit testing with phpunit in my Quality Assurance on PHP projects series. In part one we started writing unit tests for a simple game of tic-tac-toe. In part two we started converting our unit tests into actual code and moved our general unit test code for grids into a Grid focussed unit test. In this part, we're looking at how we can optimize the tests for our players.


He digs deeper into the TicTacToe application and focuses first on the single-player functionality, checking the symbol for the current player (an "X" or "O") and throwing exceptions in the code when things aren't right. He also shows the tests for checking on "more than one player" and "cannot add more than two players" scenarios. Full code for the Player class and tests are included.

2011年8月26日星期五

Site News: Popular Posts for the Week of 08.26.2011

Popular posts from PHPDeveloper.org for the past week:

PHPBuilder.com: Getting Started with the Fuel PHP Framework


On PHPBuilder.com today Jason Gilmore has a new tutorial showing you how to gets started with the FuelPHP framework, a relatively new framework-on-the-block that will feel familiar for users of CodeIgniter and Kohana.



As it happens, there are even frameworks available for those developers wishing to take advantage of the very latest PHP features such as closures and namespaces. Two such solutions are the aforementioned fat-free microframework and another relative newcomer called Fuel. Although only about 18 months old, the Fuel project has gathered a significant head of steam which powered it all the way through the recent official 1.0 release.


He talks about some of the key features of the framework including its command line tool, oil, and how nicely it plays with the ideas of a RESTful API. He walks you through the installation of the framework and how to create a sample project with oil. He also briefly touches on the default controller, view and templating structure.

Christian Weiske's Blog: Working with .phar files


Christian Weiske has a new post to his blog looking at a feature of PHP that's very useful yet doesn't seem to be widely used - phar archives. His post introduces you to phar and includes the good and the bad about their use.



It is possible to pack an entire PHP web application up in one single file and run it without unpacking it. This files usually have a .phar extension, which is an acronym for PHp ARchive, loosely based on jar (Java ARchive). [...] With PHP 5.3.0, the Phar extension is an official part of PHP. Shipping your applications as Phar thus is safe since 5.2 has reached its EOL already.


He mentions some of the pros (like one file, no unpacking needed) and cons (like no method for incremental updates, changing individual files inside the package is hard) of using them. He also talks about some of the tools you can use to create your own packages including PHP's own support, phar-util and Phing's phar task. He includes a few "things to consider" when making your packages and gives examples from the SemanticShuttle package to illustrate. Thrown in at the end are some benchmarks that show the difference between static file serving (with and without PHP) and the same sort of statistics with Phar packages included in the mix.

2011年8月25日星期四

Site News: Blast from the Past - One Year Ago in PHP

Here's what was popular in the PHP community one year ago today:

IT World: Lost programming skills


On IT World there's an interesting article about the programming skills that seem to be lost in today's coders and how what they may not know might hurt them in the end.



Some of these skills aren't likely to be needed again, any more than most of us need to know how to ride a horse or (sigh) drive a manual-transmission vehicle. But other skills and "lessons learned" may still or again prove relevant, whether developers are banging their heads against legacy systems, coding for new mobile and embedded devices... or other devices and applications we haven't yet thought of. [...] Here's what some industry veterans and seasoned coders think the younger generation doesn't know ... but should.


He's broken it up into a few different sections - one dealing with the lack of general hardware knowledge by a good section of the today's developers, another noting that programming is not the same as software engineering (yes, really). He also touches on the lacking idea of "thinking before coding" and how planning for errors has become less and less of an importance.

Srdjan Vranac's Blog: Custom Repository with DIC in Symfony2


Srdjan Vranac has a new post to his blog showing you how to create a custom repository with the dependency injection features that already come with the Symfony2 framework.



I am currently working on some Symfony2 bundles, I needed a custom repository to house hold my custom queries, that part is easy with sf2, and quite nicely explained in the Manual.


He walks you through the setup of a simple custom repository (a part of a Code4Hire bundle) and a (less elegant) call that can be used to reference it and its methods. To make things a big more clean and take advantage of the full dependency injection features of the framework, he makes a change to move the repository into the services.xml. This defines the container and makes it available to the application directly in function calls (like his render() example near the end of the post).

2011年8月24日星期三

Community News: Latest Releases from PHPClasses.org

David Stockton's Blog: Zend JSON - An Introduction


David Stockton has a new post to his ZendTutorials.com site today introducing you to an increasingly more handy Zend Framework component that can make your messaging needs easier. The new tutorial introduces you to Zend_Json, a component for generating and parsing JSON messages.



In the past few years, JSON, or JavaScript Object Notation has seemed to overtake XML and other data encoding methods on the web. [...] I've also seen numerous examples of developers who create their own sort of JSON encoder rather than either using json_encode or using Zend_Json. What inevitably comes back to bite them is when the data they are encoding contains a special character like quotes, colons, curly brackets, etc.


He demonstrates how the Zend_Json component helps to alleviate some of the worries with built-in features that handle everything from basic encoding/decoding, printing out results in a "pretty" way and a handy way to include executable Javascript (once it's evaled on the other side) in your payload. He finishes the tutorial off with a mention of a very handy method that will please those already having to work with XML - the fromXML() method that automagically converts the data over to JSON for you.

Project: Zend Framework Google Analytics Code Generation


Martin Aarhof has put together an handy tool for Zend Framework applications that creates the async javascript analytic code recommended by Google to provide tracking information back to Analytics.



It supports: browser Settings Detection, campaign Duration, campaign Fields (custom), cross-domain linking and last but not least Ecommerce tracking.


The configuration lets you set the various keys for your Analytics accounts, the domain name for it to live under, browser detection settings and various other settings for campaign configuration and domain setup. You can find the full code on his github account ready to download or clone.

2011年8月23日星期二

Community News: Latest PECL Releases for 08.23.2011

Latest PECL Releases:

Michelangelo van Dam's Blog: Quality Assurance on PHP projects - PHPUnit part 2


Michelangelo van Dam has posted the second part of his look at PHPUnit in his "Quality Assurance in PHP Projects" blog post series. This is a continuation from part one.



I hope everyone enjoyed my first article on unit testing with phpunit where I started writing a few tests that would guide us building our little game of tictactoe. Today I'm going start with turning these tests into working code and adjusting our tests to have a clear separation of responsibility. Since we already know what the code should produce, we only have to work out the details.


He picks up where he left off on his "tic-tac-toe" example by defining some of the classes that will be needed to fulfill the tests and a sample test to check the generated grid's contents. He includes the Grid class that will do the job (full code included) and a full test case class that runs his example with checks on testGameGridIsSetAtStart, testGridCanPositionASymbol, testGridHasThreeSymbolsInARow and testGridHasThreeSymbolsInAColumn, some with their own data providers.

Gonzalo Ayuso's Blog: Building a small microframework with PHP


In investigating microframeworks and some of the offerings out there Gonzalo Ayuso has done a little exploring of his own. He's worked up a basic microframework and shared it in a new post as a sort of academic exercise.



Nowadays microframewors are very popular. Since Blake Mizerany created Sinatra (Ruby), we have a lot of Sinatra clones in PHP world. Probably the most famous (and a really good one) is Silex. But we also have several ones, such as Limonade, GluePHP and Slim. Those frameworks are similar.


He looks at how several of these frameworks handle routing and setup, mostly using the closures/anonymous function callbacks available in PHP 5.3. His simple example framework does some basic URI handling to find the requested module, class and function (action) to call. You can even define the output format from options like json, txt, css, js and jsonp. A sample "controller" is included with a "Hello world" and there's a mention of some other options he's exploring including Twig and Assetic integration.

Gareth Heyes' Blog: PHP CSSReg


Gareth Heyes has a recent post pointing out the port of a project of his, CSSReg (a filtering tool for user-provided stylesheets) over to PHP.



Just a quick post to mention the excellent work by Norman Hippert aka @thewildcat, he successfully converted my Javascript based CSSReg into PHP. I was meaning to do this but never found the time so it's pretty awesome that not only did thewildcat convert the code but found some nice bugs in my code and fixed them. Great work Norman thanks very much!


You can see a demo of it here and grab the source as a download here. You can find out more about the origins of CSSReg (and some of its siblings) in this other post from Gareth.

2011年8月22日星期一

Community News: Latest PEAR Releases for 08.22.2011

Latest PEAR Releases:

Added Bytes Blog: If PHP Were British


On the Added Bytes blog there's a humorous post about what PHP would be like if it were British:



When Rasmus Lerdorf first put PHP together, he - quite sensibly, despite his heritage - chose not to write it in Greenlandic or Danish. [...] He opted instead, being in Canada at the time, for the local tongue. No, not French - that bastard dialect of the Queen's English commonly referred to as "US English". PHP developers in Britain have been grumpy about this ever since. What was he thinking?


Suggestions include replacing the $ with £, more correct "Hello worlds" and comments on abbreviations in function names, eloquence in control structures, spelling, manners and class(es). Check out the comments for more lovely puns.

DashExamples.com: Capture Content Security Policy (CSP) Violations in PHP


From DashExamples.com there's a quick post on how you can set up your application to notify you on content security policy violations and store them back on he server side for later review.



When somebody violates your CSP rules, there is a great feature that can setup for supporting browsers to send back the violations to your server to be saved, processed or whatever. This is a great feature because you can stop a possibly malicious piece of code from executing and learn which scripts may have vulnerabilities in your code.


The reports as delivered by the browser back to your server according to your site's policy setup. They're sent back as a JSON string that is easily parsed and stored. The post shows you a sample database table structure (storing things like request, headers, blocked location and IP address) and the PHP to handle the incoming post. For more about the CSP reports, see Mozilla's example on their Developer section.

CodeIgniter Blog: GitHub, Reactor, and v2.0.3


The CodeIgniter blog has a a new update today with some changes that are happening in the project and it's community.



If you are following CICON 2011 today, then you no doubt already heard from the Reactor team: CodeIgniter is now using Git for source control, and has moved its home to GitHub. Also, CodeIgniter "Core" is not longer being publicly maintained. CodeIgniter "Reactor" is CodeIgniter, so we are dropping that suffix. In short: CodeIgniter is the framework, and Reactor is our community driven development program.


As a part of the move they also released a new version of the formerly-Reactor codebase. The EllisLab blog has more information about the git switch including their reasons and some of the immediate effects they see from the change.

2011年8月19日星期五

Site News: Popular Posts for the Week of 08.19.2011

Popular posts from PHPDeveloper.org for the past week:

Robert Basic's Blog: Debugging two PHP projects in Netbeans at the same time


Robert Basic has posted a quick hint for Netbeans users on how they can debug two (interlinked) projects at the same time in the same debugger instance.



I'm currently working on some Symfony2 bundles and I have one Netbeans project for the main Symfony2 app and one project for the bundle. [...] The debugger starts for the "main" project, which is the Symfony2 app, but setting breakpoints with Netbeans (y'know, by clicking the line number) for the bundle doesn't really work, as those are in the other project and not in the debugged one, rendering the whole debugging useless.


The fix is pretty simple, if a bit manual - simply place xdebug_break calls in your code anywhere to tell the debugger to stop there. It's not as friendly and automatic as just clicking in the IDE, but it gets the job done. For more information on Xdebug, see their site.

PHPClasses.org: Top 10 Wrong Ideas About PHP That You Should Get Right


On the PHPClasses.org blog there's a new post that tries to right some wrongs about how people think about PHP. Maunel Lemos looks at some of the misconceptions people have about the language and the truth behind them.



PHP is often a misunderstood language by people that either love or hate it. [...] This article attempts to clarify some of the most common wrong ideas that many developers have about PHP. Read the article to the end, so you may eventually start having a better perspective about PHP and take advantage of the opportunities that this language and the PHP ecosystem can provide you.

Among the misconceptions on the list, there's things like:



  • PHP cannot do X (access memory, control hardware devices, or some unusual purpose)
  • PHP is controlled by only one company (Zend)
  • PHP is worse than Ruby On Rails, Python Django, X language Framework
  • PHP is not good for high performance scalable Web sites or applications
  • PHP developers are cheaper because they are not qualified

Dzone.com: Object Calisthenics


Giorgio Sironi has a new post on DZone.com today with a look at what he calls "object calisthenics", a sort of ">workout exercise for you to do to flex your object-oriented programming skills.



Calisthenics is a Greek-derived term for exercises, in the gym sense. I have object calisthenics, exercises for object-oriented programming, around for a long time and saw them as fascinating, but never got the time to try.


The challenge he lays out includes rules relating to indentation levels (really complexity levels), wrapping primitives in strings, small entities and using first-class collections. To illustrate, he works through a solution to the prime factors kata and breaks it down into the eight different rules complete with code examples.

2011年8月18日星期四

Site News: Blast from the Past - One Year Ago in PHP

Here's what was popular in the PHP community one year ago today:

James Fuller's Blog: Adding a Session Flash Message to your site in Lithium PHP


James Fuller has a new post to his blog today showing how to use flash messaging in the Lithium PHP framework.



In my case, I needed to display to the user a "flash message" after redirecting them to another page. CakePHP has this as part of the framework by default but Lithium will ask you to do a bit more work. Luckily, Lithium framework lead developer Nate Abele has created a handy extension to the Lithium session helper will will give us exactly what we need.


For those not familiar with what a "flash message" is, he defines it as a message available to the next page load with relevant information about the previous page. He includes the instructions on how to get the extension for this working in Lithium - downloading, configuring and adding the output variable for the flash messaging to your layout. He also includes an example of how to set the message so it'll be saved into the current session.

PHPBuilder.com: PHPUnit Fundamentals: Setting Up and Tearing Down a Doctrine 2 Database


New on PHPBuilder.com today is a tutorial showing you how to use set up and tear down methods in PHPUnit unit tests to work with a Doctrine 2 database, making it simpler to run self-contained testing.



The recently released Doctrine 2 presents significant advantages over its 1.X predecessor, advantages which are even more pronounced when compared to the Zend Framework's default database solution, namely the Zend_Db component. [...] When running unit tests which vet various aspects of your database you'll want to setup (create) and teardown (destroy) the test database, ensuring that a pristine and repeatable version of the database is available to each test.


He includes an example of using the SchemaTool class (of Doctrine) to drop and recreate the schema from scratch with the end result of a clean working copy, ready to test from. He also includes an example of how to initialize the database with some default information using the PHPUnit database connection and a default set of fixtures (defined in YAML).

Kristina Chodorow's Blog: Writing a PHP Extension (Four Part Series)


Kristina Chodorow has posted a four part series of articles to her blog that shares some of her experiences in developing an extension for PHP (on C/C++). It walks you through the entire process - from the basic "hello world" out to working with more complex data structures.



A PHP extension allows you to connect almost any C/C++ code you want to PHP. This is a 4-part tutorial on how to write an extension. [...] Almost all of the code examples in this tutorial are available on Github.

The parts of the series cover:




Each step comes with some good explanation, code samples and some advice on common tasks and pitfalls along the way.

2011年8月17日星期三

Community News: Latest Releases from PHPClasses.org

Court Ewing's Blog: Create and Validate a Choice List in a Symfony 2 Form


Court Ewing has written up a new post to his blog about creating a "choice" list (a select list as defined by Symfony 2) with dynamic options and validating the resulting submission. His example uses Doctrine 2 entities to work with most of the data handling.



A standard select list can be created using Symfony's choice field type; it is pretty clear how to create a new choice field with simple, non-dynamic options (e.g. gender), but it gets a little more complicated when you want to create and validate a dynamically generated choice list.


He includes the code for a simple entity, a Post model to fetch the category information and the set up of the form element - a select list of post types/categories. He also includes a bonus section showing how you can achieve the same thing without a model to bind to.
The code's a little bit more complex than the previous example, but it's basically just reproducing some of the validation and fetching logic manually.

Ade Slade's Blog: Implementing Twitter sign-in with Silex and PHP


Ade Slade has written up a quick new post to his blog today showing how you can use the lightweight Silex framework to link your login with Twitter and validate users from their API.



For those not acquainted with Silex: Silex is a PHP microframework for PHP 5.3 A microframework provides the guts for building simple single-file apps. It's awesome. For the example, I've setup a virtual host of example.local on my development machine.


He includes the contents of the .htaccess you'll need to get the rewrite to work for Silex, a link to the OAuth extension you'll need to install for PHP and the code to make the login and auth routes. You'll need to create a Twitter application for your site to get the OAuth secret key to make the authentication work. You can see the complete code here.

Michelangelo van Dam's Blog: Quality Assurance on PHP projects - PHPUnit part 1


Michelangelo van Dam continues his "Quality Assurance in PHP projects" series in his latest post, the first of a few, about using PHPUnit to test your application.



Of all tools available for improving quality assurance, there's one tool that is the core tool you have to master: PHPUnit. PHPUnit is a complete testing framework crafted by Sebastian Bergmann (@s_bergmann), who ported existing xUnit frameworks to PHP. And with this testing framework you're able to test your functionality in an automated way before you push code into production.


Michelangelo walks you through the installation (via the PEAR installer), creating a phpunit.xml configuration file and making a basic bootstrapper to define some paths and environments. To make the tests a bit more relevant than just pseudo-test examples, he's created a set of tests based around a tic-tac-toe application in a test-driven design fashion (tests first, then code). In this first part he sets up some of his assertions in the tests, but you'll have to wait until part 2 for the code that will make them pass.

2011年8月16日星期二

Community News: Latest PECL Releases for 08.16.2011

Latest PECL Releases:

NetTuts.com: Getting Started with the Fuel PHP Framework


On NetTuts.com today there's a new tutorial from Philip Sturgeon about how you can get started with Fuel PHP, a framework for rapid website development.



This two-part tutorial will get you up and running with the Fuel PHP framework. We'll start with the basics, and then move onto some more advanced topics in part two! Let's get started.


He starts with a brief introduction to the Model/View/Controller design pattern just to be sure you're up to speed with the moving parts of the tutorial. From there he walks through installation and the creation of a first "hello world" controller and view. He looks at some of the configuration options the framework includes specifically the database settings. He also points out a handy tool the framework comes with - the "oil" command line tool that makes scaffolding out an application simple. He also talks about database migrations, templating, forms and validation and tasks.

RubySource.com: PHP to Ruby: Modules, Mixins and Ducks


In his latest article comparing some of the functionality of PHP to Ruby, Dave Kennedy looks at modules, mixins and ducks and how they compare to PHP's interfaces and abstract classes.



If you have been writing PHP for a few years you will no doubt have come across Interfaces and Abstract classes. They were introduced in PHP5 object model and since have had medium usage in the PHP world. If you Google "PHP Interfaces" you will get some results on the official documentation and the rest saying how pointless they are. Why the divide? I believe it is mainly down to lack of understanding to what interfaces give you. They imply what your classes should do, but that's it. Yep, we are talking programming contracts.


He starts with some code examples of an interface and a class that implements it (to work with PDFs). He makes an abstract class to extend the functionality even further and allow for different kinds of reporting PDFs to be generated. From there he moves into the Ruby world, showing examples of duck typing and modules to avoid duplication (mixins).

DevShed: PHP and the Law of Demeter


On DevShed today there's a new tutorial looking at how to use dependency injection to help prevent you from breaking the "Law of Demeter" in your application's structure.



When [responsibilities aren't well defined for classes], it's a clear symptom of a common issue known as the "Law of Demeter" breakage. In case the name doesn't ring any bells, the "Law of Demeter" (http://en.wikipedia.org/wiki/Law_of_Demeter) - or the Principle of Least Knowledge - is a paradigm that allows to create loosely-coupled classes, based on a simple concept: each class should be designed to work properly using only the dependencies that it really needs.


He talks about how violation of this law (whether you knew you were or not) can lead to some bad coupling practices. He includes a few classes under a SampleApp that handles the interface between a database and the domain model. The violation of the law comes in when the database and service layers are introduced - a fetch the code does to get an adapter from the service locator rather than directly from the database functionality as it should.



There's code for everything included in the post

2011年8月15日星期一

Community News: Latest PEAR Releases for 08.15.2011

Latest PEAR Releases:

Mike Purcell's Blog: Symfony - sfGuardPlugin - Use Email Instead of Username


Mike Purcell has a handy new post for the Symfony users out there wanting more flexibility with their sfGuardPlugin use in their application. He describes how you can use email instead of a username for working with the user information.



sfGuardPlugin is pretty awesome. It allows a symfony developer the ability to quickly implement a user login and access control system. However, there is an issue with respect to telling the plugin whether to use the username or the email column for validating user submitted input. After some Googling I found a few sites which forced sfGuardPlugin to use email rather than username, but only after quite a bit of work. What I am going to show will accomplish the same end goal, but with minor changes.


He starts with a look at the validator class, showing how the values are going to be passed to the backend. The plugin makes a call to a "retrieveByUsername" method to get the user's information, but his method overrides this...sort of. His method actually contains the query to fetch the user information by email instead. This is useful if you want to use the email address as a username for the site but still want to maintain data integrity on the user records (valid emails can then be used for auth and for sending messages).

Stuart Herbert's Blog: PHP Components: PHP Components: Shipping Unit Tests With Your Component


Stuart Herbert has his latest post in his "PHP Components" series on his blog today - a recommendation to include unit tests along with the release of you component.



I'm now going under the bonnet of our components, and looking at the different file roles that the PEAR installer expects to find when we distribute our component as a PEAR-compatible package. One of the most important file roles allows you to ship your tests with your package - and it's vital that this is something that you get in the habit of doing routinely.


He recommends "testing your code and shipping your tests" along with the component(s) you're releasing. Not only does it help you create a better quality end result but also makes it simpler for other developers to make changes and know they're not breaking things. He describes unit tests for those not familiar and includes a specific example of the CommandLineLibrary and its related tests.

Hyperpolyglot.org: Syntax for Common Tasks - Side-by-side (Ruby, Perl, Python & PHP)


On Hyperpolyglot.org there's an interesting listing of scripting language syntax - PHP, Python, Ruby and Perl - showing some of their common syntax and data structures side by side.



Sections of the reference sheet include



  • arithmetic and logic
  • arrays
  • execution control
  • libraries and modules
  • objects
  • reflection


It's interesting to see how the various languages compare, where some have shortcuts for things and others fail at the same (or make it much more difficult). Descriptions for the different row types are also included.

2011年8月12日星期五

Site News: Popular Posts for the Week of 08.12.2011

Popular posts from PHPDeveloper.org for the past week:

David Stockton's Blog: Changing ErrorController to work with AJAX


David Stockton has a new tutorial posted to his blog - a technique he's found useful in his Zend Framework application to make the ErrorController work with Ajax calls to reduce the message you get back to just a JSON response.



If you've ever built a Zend Framework MVC app which makes AJAX calls, you may have noticed that if an error occurs, you'll get a chunk of JSON followed by the HTML for the error page. If you've built a layout, you'll get all of that back to. This is fine if your users hit the page in the browser but it can cause problems with your JavaScript being able to correctly decode your JSON.


The fix is pretty simple, though, and only requires that you add the error handling action to the Ajax context to force it to drop the layout and any other HTML that might come along with the view. He includes a bit more code to have the error handler include the exceptions and pass them out to be included in the JSON response.

DZone.com: Hardening PHP: SQL injection - Complete walkthrough


On DZone.com today there's a new post from Krzysztof Kotowicz sharing a presentation of his about protecting your application from SQL injection.



The materials teach how to use prepared statements, how to escape and write secure stored procedures. Many PHP projects are covered - PDO, Propel, Doctrine, Zend Framework and MDB2. Multiple gotchas and caveats are included. I discuss why escaping is usually the wrong choice, which practices to avoid or follow and how stored procedures sometimes offer no protection at all.


The presentation (as posted to Slideshare) starts with some of the basics - what SQL injection is and an example of how it could be used to bypass security. He covers how to use prepared statements in each of the technologies (with code snippets), methods for escaping data and how to create stored procedures that are protected from the same threats.

Rafael Dohms' Blog: Filtering objects using annotations


Rafael Dohms has an interesting new post to his site today looking at a library he's developed (inspired by the Symfony Validation library) to help filtering values with rules defined in annotations.



PHP does not have native Annotations support, however many projects have been using doc blocks to add value and semantics to code, like PHPUnit, Doctrine and Symfony. The Doctrine did a really good job in making available a Annotation parser kit, which allows you to bring the power of annotations into you own project. This opens up a few possibilities.


He shows the current use of the Validation library with a sample check of a $name variable for "not blank". His tool, DMS, extends this functionality and gives you access to both custom filtering methods and standard PHP functions to filter the resulting variable value. He includes an example showing two variables with filters StripTags, StripNewlines and Trim as well as the code to execute the filtering. You can get the library either ready to integrate with Symfony/Doctrine or as a standalone tool.

2011年8月11日星期四

Site News: Blast from the Past - One Year Ago in PHP

Here's what was popular in the PHP community one year ago today:

Sourcefabric Blog: Why Sourcefabric chose Zend as our PHP framework.


On the Sourcefabric blog today they've posted their reasons for choosing the Zend Framework to rebuild their applications in - Newscoop and Airtime.



Back in the Fall of 2010, we needed a new PHP framework for our applications. Neither of our applications - Newscoop or Airtime - had anything that could really be called a framework, though our code was generally separated into Models, Views, and Controllers (MVC). But it wasn't pretty. We were in need of an established MVC framework to build on.


They tried out several different frameworks including Yii, CakePHP, Kohana, Symfony and, of course, the Zend Framework. They talk briefly about their evaluation process and some of the pros and cons they found along the way.



Overall, using Zend has helped us to create clean, structured code and for most cases has lowered our implementation time for new features. [...] Even though there are some things that could be better, the net benefit has been positive for us.

David Stockton's Blog: Using local configuration files in Zend Framework


David Stockton has a new post to his site looking at a handy tip those using the Zend Framework for their applications can use to simplify how they handle their settings - using local configuration files.



I've run into a common issue [in my Zend Framework development]. This issue is multiple developers each needing a slightly different configuration from each other. Inevitably this means that each developer needs to maintain their own changes to a common configuration file. This tutorial shows you how to make some minor modifications to your Zend Framework MVC application to allow developers to supply their own local.ini which is not checked into the repository and can override any settings they want while not having to worry about any of the problems listed above.


He walks through the changes you'll need to make - a simple update to the bootstrap that uses Zend_Config_Ini component with the "allowModifications" setting set to true. A check is then put in to see if there's a "local.ini" file in the configuration directory and, if so, load it and potentially override the application.ini settings. It's a very handy tip for those working in a shared code base not wanting to step on any toes.

2011年8月10日星期三

Community News: Latest Releases from PHPClasses.org

Anthony Ferrara's Blog: On Optimization in PHP


Anthony Ferrara has a new post to his blog today looking at something that's constantly a focus of user-facing applications, PHP ones or otherwise - application optimization. He specifically discusses handling it in PHP and some things to keep an eye out for.



When it comes to optimization, there are two competing viewpoints in the PHP community. Some say that optimization should only ever be an after thought and to avoid premature optimization at all costs. Others will say that this is impractical, and you should make your application fast as you write it, since then you won't have to go back and clean it up to make it faster. While I can understand the viewpoints of both sides, I am firmly in the former category.


He talks about the "90/10 Rule" of development (most of the work is done by only a small part of the code) and what that critical 10% could be made of. He also touches on the "60/40 Rule", "instinctual optimization" and the emphasis people put on benchmarks for their tool or framework of choice.

Slawek Lukasiewicz's Blog: Throwing Exception with Type Hinting Failed


Slawek Lukasiewicz has a helpful hint posted to his blog today about handling type hinting failures in a what he sees as a "more correct" way than just throwing an error - throwing an exception when the hinting criteria's not met.



One of the most annoying behavior of PHP type hinting feature is triggering error instead of throwing exception when instance type is invalid.


By default, a failure generates a "catchable error" that, thanks to the custom error handling methods PHP includes, can be correctly handled. He includes a snippet of code that defines the errorHandler method that checks the error type for E_RECOVERABLE_ERROR and throws the exception (an ErrorException) if found.

PHPBuilder.com: Smarty PHP Template Engine: Building PHP Apps in a Flash


On PHPBuilder.com today there's a new tutorial from Octavia Anghel introducing you to Smarty, a PHP-based templating engine that can make creating the layouts and output of your site simpler and easier to reuse.



Smarty is a template engine for PHP whose main goal is to facilitate a very useful way to separate the business logic from the presentation logic. This article introduces Smarty and demonstrates how to install the template, create an application from scratch and interact with a database.


Installation of the tool is simple and using it is as easy as including the Smarty class, configuring it a bit through method calls and outputting to a template (tpl) file. A both a "Hellow World" and slightly more complex example using database results to build a table are included.

2011年8月9日星期二

Community News: Latest PECL Releases for 08.09.2011

Latest PECL Releases:

Bradley Holt's Blog: The Case For Rapid Release Cycles


Bradley Holt has a new post to his blog today talking about something he's a fan of in his development processes - rapid release cycles - and how something like the Zend Framework could benefit from it.



There has been some discussion recently on the Zend Framework mailing list around release cycles. I proposed a release cycle of six months for major versions (someone else suggested eighteen months, which may be more reasonable for a framework). Rapid releases allow one to accelerate the cycle of building, measuring, and learning. Gathering data from actual usage (measuring) provides an opportunity for learning that can be applied to the next release (building).


He points out that the post isn't specifically targeted at the Zend Framework project, merely that it was the inspiration point for the idea. He talks about what rapid release cycles are and what it can give the team that implements it - less worries about backwards compatibility breaks, a potential encouragement for development pacing and the ease for the customers doing upgrades.



A rapid release cycle allows you to apply new learning, knowledge, and perspective as often as possible. Do your best today, and give yourself opportunities to do your best in the future as well.

Martin Sikora's Blog: Storing arrays using JSON, serialize and var_export


Martin Sikora was working on an application that used a large dataset (in an array) and found some interesting things in regards to PHP's resulting loading time and saving time in four different types of arrays.



Recently I was dealing with precessing and storing large arrays in PHP (around 100 000 items) and I found out some quiet surprising facts that are very useful in performance critical applications. [...] When I started looking for some benchmark I found article Cache a large array: JSON, serialize or var_export?. That is really good but I wanted to compare a few more things.


He tested with four different array types including associative with an integer value and numeric index with a string value at sizes of 10, 100, 1,000 and 10,000 items. He ran his tests with the json methods, serializing them and a var_export. There's graphs of his results for each included in the post with some interesting variations between the different array types.

Sameer Borate's Blog: Checking your site for malicious changes


Sameer Borate, in the wake of having security issues with his site, has posted a hint you could use to help detect when something has changed in important files in your application by checking their hash.



Today a couple of hours back my site got compromised. Not much changes to the code, but the .htacces was changed and some code [...] was added to the .htaccess file, which redirected the traffic coming from search engines to a malware site. It has now been removed and to prevent any such changes to the .htaccess file in the future, I've written a small php script that compares the hash (SHA1) of the two major files that usually get compromised and compare them to the one originally stored.


It's not a preventative measure by any means, but it can help you keep track of if something's changed. Several issues have popped up in the major blogging engines that allow for changes to be made directly to files. These changes result in the sha hash to be different and can be used to trigger a security alert. His sample code shows a basic call to mail an alert, but it could be as complex as you'd like (possibly even logging to a database or the like).

2011年8月8日星期一

Community News: Latest PEAR Releases for 08.08.2011

Latest PEAR Releases:

Wojciech Sznapka's Blog: Symfony2 stable is available, what's the big deal?


For those not familiar with the Symfony PHP framework, all of the hype surrounding its version 2 release might seem a little too much. Wojciech Sznapka has a new post that tells you why it's such a "big deal" and what you could expect from it.



On July 28th Symfony2 was finally released, with launch parties all over the world. Developers are excited, managers are excited and whole ecosystem is happy. They're right, there are plenty of reasons to be optimistic. symfony 1.x is a great framework, I made many projects with it, nevertheless Symfony2 is a new way of doing things in PHP. I observe, that applications made with symfony 1 tends to be messy with raising number of functionalities. There too many magic tricks, which you can use, which are hard to manage in big, multi-team projects. Symfony2 does it smarter.


He lists a few things that are larger changes in Symfony2 including a cleaner templating system for views (Twig), a focus on reusability, the bundling of Doctrine2 for ORM/database support and other updates like namespace support, PHPUnit compatibility and code generators.



You can find out more about the project (and how you can contribute) on the framework's website.

Gonzalo Ayuso's Blog: Runtime Classes. A experiment with PHP and Object Oriented Programming


Gonzalo Ayuso has put together an experiment related to the current OOP structure of PHP - a test working with runtime classes, a structure generated entirely when the script is executed and not predefined in the file.



Last week I was thinking about creation of a new type of classes. PHP classes but created dynamically at run time. When this idea was running through my head I read the following article and I wanted to write something similar. Warning: Probably that it is something totally useless, but I wanted to create a working prototype (and it was fun to do it).


His class is pretty basic - a "Human" object that echoes a "hello world" sort of message via a "hello()" method. He creates the classes inside of different test methods to ensure that his assertions are true. The tests check basic output of the "hello()" method, calling undefined methods, testing inheritance and a test creating and evaluating a dynamic function.



For something more complex, he creates a dynamic class that solves the FizzBuzz kat, a popular programming puzzle. You can find the full code for this and his other examples on github.

Dave Marshall's Blog: Traits in PHP 5.4 - HelloWorld with Logging Trait


Dave Marshall is already looking ahead to the next major release of PHP, version 5.4, and one of the features it will include - traits. In this new post to his blog, he introduces a "logging trait" he's come up with to make logging simpler in your (Zend Framework) application.



One of the 'traits' I find myself constantly adding to library files is optional logging of it's behaviour. The library class has it's own log method, that checks to see if the instance has had a logger injected and if so, logs the message. I see this as a perfect candidate for becoming a reusable trait, as I tend to have the same code copy/pasted throughout my library classes. The problem is, according to the rfc, traits aren't supposed to have state/properties, which makes it difficult to have a DI setter method in a trait.


He includes the code for his trait example (noting that it may or may not end up working correctly in the 5.4 final release) that sets a logger on a sample class and logs a few values out to the console. It's a simple example, but it shows you one of the most useful things about traits - the "drop in resuability" nature they allow in your libraries and classes.

2011年8月5日星期五

Site News: Popular Posts for the Week of 08.05.2011

Popular posts from PHPDeveloper.org for the past week:

Community News: PHP 5.4 alpha3 Released for Testing


The PHP development group has officially released the alpha3 of PHP 5.4 as ready for testing. Rasmus Lerdorf comments:



PHP 5.4 alpha3 is available for testing now. Please give us a hand and compile it on your platform and run a "make test". Download it from http://qa.php.net and you can see the changes in the NEWS file at http://t.co/bBVGj8P


Updates in this alpha include the shortened array syntax, binary numbers format, support for the "Class::{expr}()" syntax, removal of magic quotes related features, a change to include E_STRICT in E_ALL and several others. Head over to the PHP QA site and download this latest version to test in your environment. Remember, environments are unique, so the more test results the better - it helps make for a better quality end result.

DZone.com: Assetic: JavaScript and CSS files management


On DZone.com today Giorgio Sironi introduces you to Assetic, an asset management tool that helps you keep things organized and easily requested by your application.



Assetic is a PHP library for managing the deployment of your assets: JavaScript, CSS and other resources which will be requested by the browser. The library has been created by Kris Wallsmith from OpenSky, an e-shop where many of the active members of the PHP community work, or worked (see Jonathan Wage/Doctrine 1 and Bulat Shakirzyanov/Imagine.)


Giorgio compares it to the more traditional method (putting them in a public folder) and how Assetic gives you an advantage over this setup. The main feature of the tool is to bundle all of your assets into one file that is then sent to the browser and interpreted there reducing the need for HTTP calls to request multiple files. An example is included showing the creation of an asset collection and the output of the files all combined into one string.

2011年8月4日星期四

Site News: Blast from the Past - One Year Ago in PHP

Here's what was popular in the PHP community one year ago today:

Matthew Weier O'Phinney's Blog: Using DocBlox


On his blog today Matthew Weier O'Phinney has a new post looking at an alternative to some of the other PHPDoc-based documentation tools, DocBlox, a tool written in PHP.



Until a few years ago, there were basically two tools you could use to generate API documentation in PHP: phpDocumentor and Doxygen. [...] phpDocumentor is practically unsupported at this time (though a small group of developers is working on a new version), and Doxygen has never had PHP as its primary concern. As such, a number of new projects are starting to emerge as replacements.


He introduces DocBlox as one of these alternatives and points out where you can get the latest version (from one of many sources including github, PEAR or by just grabbing a release. He includes instructions on how to run the tool on your code, use it to identify missing docblock comments and how to use the class diagrams feature that gives a more visual sense of how things fit together. He also mentions changing the title of the output, using different templates and how it uses a local SQLite database to cache the parsed information about your code (making it simpler and faster to do updates in the future).

Zend Developer Zone: ZendCon '11 Alumni Discount


On the Zend Developer Zone today Cal Evans reminds you about the alumni discounts you can get for this year's ZendCon if you've attended the conference in the past years.



Ah the memories of ZendCon...there are just so many of them. Great session, Keynotes that inspire you to think, and some of the parties can only be described as epic. Alumni, you know what I mean, so join us again and continue the tradition. You know why you should be there, you've done it before and experienced it yourself. So don't put off registering any longer.


The discounts can give you anywhere from $50 USD to $100 USD off the ticket price and if you get tickets before September 10th you can get these discounts off of the already discounted Early Bird prices. You can get your tickets here.

Martin Psinas' Blog: Switching to PDO


In a new post to his blog Martin Psinas talks about some of his pains experienced with upgrading his code to use PDO instead of the mysql extension for database interaction.



I read not too long ago that the mysql library in PHP is being deprecated as of v6.0 in favor of mysqli or PDO, so of course I had to update all of my database code keep on top of things. I spent about 5 or 6 hours over the course of 2 days familiarizing myself with the new syntax and updating my code offline. Without any testing, I decided I could go ahead and push the code "live" because I'm just that over-confident sometimes, although I did make a backup in case anything went wrong (or so I thought).


Two problems jumped out immediately - a SQL error caused by this bug and the other being a problem with preparing his statement inside of a session handling method.

2011年8月3日星期三

Community News: Latest Releases from PHPClasses.org

DZone.com: PHP 5.4 features poll: the results


On DZone.com today Giorgio Sironi has posted the results of a poll taken a little while back concerning what people thought was the best feature of the upcoming PHP 5.4 release.



After two weeks, we have closed the poll among the PHP community of Web Builder Zone to establish which are the most wanted features, which will influence development of applications on PHP 5.4. Hopefully this poll would also shape our focus in tutorials in the future - I personally plan to dedicate more time to the winning features.


Runners up included the removal of magic quotes and strict mode with the top three being (in this order) the upload progress patch, traits and the array improvements leading the pack. You can see the results here.

Ibuildings techPortal: Beyond TDD with PHPSpec


On the Ibuildings techPortal today there's a new post from Marcello Duarte following up on his previous post looking at behavior driven development (here) with a look at PHPSpec, a port of RSpec that is the first PHP BDD framework.



PHPSpec is the first ever PHP BDD framework. It is a port of RSpec to PHP created back in 2007 by Padraic Brady and Travis Swicegood. Development in this framework stopped for a while and was reignited last August (2010).


He goes over how to get it installed via PEAR and how to write some sample tests following along the topic from his previous post (handing videos and reviews). He gets into a bit more detail by describing how MVC is handled with PHPSpec and how the Zend Framework command line tool can be used to create a controller that satisfies the test.

2011年8月2日星期二

Community News: Latest PECL Releases for 08.02.2011

Latest PECL Releases:

Jeremy Cook's Blog: Guelph PHP Users Group


Jeremy Cook has pointed out a new post to his blog about the forming of a Guelph PHP User Group in Guelph, ON meeting on the last Wednesday of every month (starting September 28th).



Colin DeCarlo and I have been working on a PHP users group for South Western Ontario for a while and we're pleased to announce the first meeting of the Guelph PHP Users Group. The group will be meeting on the last Wednesday of every month, starting on September 28th, at the offices of Well.ca at 919 York Rd, Guelph, ON N1E 6Y9 from 7.30pm-10pm. For the first meeting Ilia Alshanetsky, chief software architect for Advanced Internet Designs Inc, will be talking about 'Hidden Features of PHP'. For the second meeting Tony Thompson, Director of Technology for MRX will be talking about the Varnish web application accelerator. We're looking for speakers for other meetings so please get in touch if you have anything you'd like to speak about.


If you're interested in attending this first meeting, head over to this signup page and let them know.

Sander Marechal's Blog: A YuiCompressorFilter for Phing


Sander Marechal has been working with Phing in some of his recent development and has created something useful for compressing Javascript and CSS files on the deployment of your application - a YuiCompressor task.



I am going to write several useful extensions, the first of which is a YuiCompressorFilter. Phing already has support for a JavaScrip minifier in the form of the JsMinTask, but the yui-compressor is more useful. Not only does it usually compress better than JsMin, it can also compress CSS files. Also, because my YuiCompressor extension is implemented as a filter instead of a task you can do fancy things like minifying and concatenating files in a single step.


He includes both a sample of the task and it's configuration (the XML) in the post as well as a link to its source over on github.

2011年8月1日星期一

Community News: Latest PEAR Releases for 08.01.2011

Latest PEAR Releases:

PHPClasses.org: Lately in PHP podcast episode 14 - PHP 5.4 Alpha Features


On the PHPClasses.org blog today they've released the latest episode of their "Lately in PHP" podcast hosted by Manuel Lemos and Ernani Joppert. In this new episode they talk about some of the features to be included in PHP 5.4.



PHP 5.4 Alpha versions just started to be released. On episode 14 of the Lately in PHP podcast, Manuel Lemos and Ernani Joppert discuss the purpose and interest of the new PHP 5.4 features already implemented in these alpha releases. They also discuss the repercussion in the PHP community of the plan to deprecate the original PHP MySQL extension.


You can either listen via the in-page player, by downloading the mp3 or by subscribing to their feed.

Iwan Luijks' Blog: Getting certified, some pro's and misconceptions


Iwan Luijks has a recent post to his blog trying to dispel some of the myths and misconceptions about becoming a certified ZCE through Zend's testing. He also includes some of the benefits of having the certification to go with your name.



In the community of PHP developers there are more non-certified professionals than certified professionals. PHP developers mostly don't really see the pro's of getting certified. These developers mostly honor the fact that PHP is a quick and easy language to learn and to get started with, and professionalism is found even by building a simple dynamic web page, leaving the discussion of whether this is a good or bad thing for what it is.


He talks about the confidence it can give current (and future) employers in your skill level and let them know you're the kind that keeps on learning/improving in your career. It also lets them know that you're dedicated enough to learn what you need to pass and can put it into practice easier in the future.