2011年9月30日星期五

Site News: Popular Posts for the Week of 09.30.2011

Popular posts from PHPDeveloper.org for the past week:

PHPMaster.com: Introducing Superglobals


PHPMaster.com is back with another introductory tutorial for those new to the PHP language. It's a look at one of the most commonly used (sometimes badly) features of the language - superglobal variables.



Superglobals are specially-defined array variables in PHP that make it easy for you to get information about a request or its context. They are called superglobal because they are always accessible, regardless of the scope - that is, you can access them from any function, class or file without having to do anything special. The superglobal variables are: $GLOBALS, $_SERVER, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_REQUEST and $_ENV. And while you can learn more about each by reading the PHP documentation, I'd like to show you the ones I think you're likely use the most.


He goes through some of the major ones and explains what kind of situations they can be used in and what data would be inside - $_POST, $_GET, $_SESSION and $_SERVER.

PHPClasses.org: Lately in PHP Episode 16 - APC in PHP, MODX CMS, Top Developers

PHPClasses.org has posted their latest episode of their "Lately In PHP" podcast today - PHP 5.4.0 Will not Include APC, Is MODX CMS better than Wordpress? Top PHP Developers in Every Country.



PHP 5.4 beta 1 was released but APC is not going to be included at least in PHP 5.4.0. Manuel Lemos and Ernani Joppert discuss this and other happenings in the PHP world, like the adoption of more robust Continuous Integration methods to prevent shipping buggy PHP versions like what happened with PHP 5.3.7.


The podcast also features an interview with Bob Ray, an author and contributor to the MODX CMS platform project. You can listen to this latest episode either through the in-page player, by downloading it directly or by subscribing to their feed and getting this and past shows automatically.

2011年9月29日星期四

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

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

Brian Swan's Blog: Version 3.0 (beta) of the SQL Server Drivers for PHP Released!


Brian Swan has a new post to his MSDN blog today about the release of the latest version (3.0 beta) of the SQL Server drivers for PHP. This new release includes three improvements - buffered queries, support for LocalDB and support for high availability/disaster recovery.



A Community Technology Preview (a beta release) of v3.0 of the SQL Server Drivers for PHP was released today (see the announcement on the team blog). You can download it here: Download v3.0 of the SQL Server Drivers for PHP. [...] It's important to note that the latter two features are dependent on the next version of SQL Server (code named "Denali"). A preview of Denali can be downloaded for free here (see notes later in this article about the installation process): Download SQL Server Denali CTP 3.


He gives brief summaries (some with example code) of what these three new features have to offer those using SQL Server in their applications. The "buffered queries" allows you to bring your entire result set into memory, making it simpler to interact with as rows/columns. The LocalDB support gives developers a quick way to have a database without the hassle of a server - just connect right to the SQL Server database file. The high availability feature has been included for a while but has a new name in the upcoming release - SQL Server Always On.

Noupe.com: Web Design & Development Podcasts


Noupe.com has posted a list of what they consider some of the best web design and development podcasts out there ranging on topics from general web tech to specific topics like accessibility and critiques of website designs.



Not long ago we had a post that discussed the role that podcasts have been playing in the design field. After which we were asked for a post that focused on more web design and development related podcasts for our readers. [...] We scoured the bountiful podcast offerings that the design and development community have on offer these days, and found some great shows to point our readers towards.

Shows in their list include:


2011年9月28日星期三

Community News: Latest Releases from PHPClasses.org

Ulf Wendel's Blog: PECL/mysqlnd_ms compared to a classic


Ulf Wendel has a new post that compares the performance of a classic method for using the mysqlnd plugin in MySQL replication to mysqlnd_ms, the replication and load balancing plugin for the mysqlnd driver (that works with the mysql and mysqli functionality and is, as of this beta of PHP, the default driver for MySQL connections).



Recently I was asked if PECL/mysqlnd_ms should be used to add MySQL replication support to a yet to be developed PHP application. The mysqlnd plugin, which supports all PHP MySQL extensions (PDO, mysqli, mysql), stood up against a classical, simple, proven and fast approach: one connection for reads, one connection for writes. Let's compare. This is a bit of an unfair challenge, because PECL/mysqlnd_ms was designed as a drop-in for existing applications, not optimized for those starting from scratch, *yell*... The plugin stands up quite well, anyway!


He starts with a look at the "classical pattern" of using a factory or singleton to make a database object instance that gives back different connections for reads versus writes (slave vs master). The mysqlnd_ms plugin allows you to define configuration settings to tell the queries to automatically go to certain places for different actions. For example, you could use "master_on_write" to tell it to use a master node if you're doing an INSERT or UPDATE versus a SELECT. He also shows a more complex example using a SQL hint and one issue that might come from the "human element" - not paying attention to database character sets.

Lorna Mitchell's Blog: PHP Developer at a Python Conference


Blurring the lines of the usual conference scene, Lorna Mitchell has posted about her experience at a Python conference as a PHP developer (and a speaker at that).



A few weeks ago, while attending the delightful OggCamp, I was approached by someone asking me to speak at PyConUK. Well ... I'm a PHP developer, but as with most PHP developers, we just like good shiny tech and aren't religious about any particular language. So I instantly said yes and then started to worry what I was letting myself in for!


She mentions being happy for attending if for nothing else than that it allowed her a look at technology outside of the usual PHP bubble. The event featured session on topics ranging from music production on linux, the Nanode project, accessibility and Lorna's "Careers in Open Source" presentation.



Attending conferences/events that apply outside of your own community can lead to some great things. Be sure to poke your head up now and again and take in the bigger picture - there's more than just one language (or sets of technology) out there. Jump in and learn from them, even if you're just a beginner.

PHPMaster.com: Preventing Cross-Site Request Forgeries


SitePoint' PHPMaster.com has a new tutorial posted today from Martin Psinas about some tactics to prevent cross-site request forgeries from happening in your PHP application. The article introduces key concepts of CSRF and how you can keep it from happening in your code.



Cross-site request forgery (CSRF) is a common and serious exploit where a user is tricked into performing an action he didn't explicitly intend to do. This can happen when, for example, the user is logged in to one of his favorite websites and proceeds to click a seemingly harmless link. In the background, his profile information is silently updated with an attacker's e-mail address. [...] Any action that a user is allowed to perform while logged in to a website, an attacker can perform on his/her behalf, whether it's updating a profile, adding items to a shopping cart, posting messages on a forum, or practically anything else.


He shows it to you "in action" with a PHP script for a basic login page that takes a username and password, does some filtering and sets the username to the session. Their "harmless.html" file offers a link to the site's "process" page with a logout action that would allow the "harmless" file access to the current session if clicked. To prevent this from happening, they suggest a unique token be included in interactions on your site. This key is checked against a token in the current session (or other location) and is only valid if they match.



The Symfony framework has included this as a part of their forms for a while now and includes automatic handling to check its validity. Solutions also exist for other frameworks like Zend Framework and many others.

2011年9月27日星期二

Community News: Latest PECL Releases for 09.27.2011

Latest PECL Releases:

Wojciech Sznapka's Blog: Loosening dependencies with closures in PHP


Wojciech Sznapka has a new tutorial posted to his blog today looking at removing some of the issues surrounding dependencies in PHP applications with the help of closures.



Today I ran into a little issue: how to pass generic logger object to method? I wanted to get some verbose output from method, which I call from Command, but onc time it should log with Symfony2 OutputInterface and other time it should use monolog logger. Of course I can make some wrapper class for both of them, but it would be kind of an overkill. The Closure from PHP 5.3 came with solution.


His alternative creates a closure for his Symfony2 application that defines the logger handling in an abstract way and injects that object into his job queue manager for handling. This way the manager doesn't have to worry about handing the mailing itself, it's just deferred to the mailing object. You can find out more about this technique, dependency injection, here.

PHPMaster.com: Regular Expressions


Regular expressions have always been something that have mystified developers, even those seasoned ones looking to match the most complicated data. If you're just venturing into the world of regex, PHPMaster.com has a good guide to help you wade through some of the basics.



It makes all the sense of ancient Egyptian hieroglyphics to you, although those little pictures at least look like they have meaning. But this… this looks like gibberish. What does it mean? [...] When you're looking to go beyond straight text matches, like finding "stud" in "Mustard" (which would fail btw), and you need a way to "explain" what you're looking for because each instance may be different, you've come to need Regular Expressions, affectionately called regex.


The include a (somewhat) complicated example regex string and break it down chunk by chunk - groupings, character sets, multiple matching, delimiters and more (the pattern matches valid email addresses). They show how to use it in PHP with preg_match, preg_replace and preg_match_all for different situations.

2011年9月26日星期一

Community News: Latest PEAR Releases for 09.26.2011

Latest PEAR Releases:

Philip Norton's Blog: Creating A Thumbnail Of A Word Document With PHP And LiveDocx


In a new post to his blog Philip Norton shares a method for creating a thumbnail of a Word document with the help of PHP and LiveDocx (in this case, the component inside the Zend Framework).



Creating Word document icons is very simple thanks to a service called LiveDocx. LiveDocx was created as a web service to allow the easy creation of most document formats from a simple template. However, it is possible to send a normal Word document as the template file and get an image of the file in return.


You'll need a LiveDocx account to be able to use the service - there's a free option of their service that uses a shared server. Included in the post is a sample script that defines a LiveDocx connection, pulls in a local Word document for parsing and calls a "getBitmaps" method on the service to return the raw image data. This is pushed into an image (using GD) as a PNG.

Phil Sturgeon's Blog: Managing CodeIgniter Packages with Git Submodules


Phil Sturgeon has a new post to his blog today for the CodeIgniter folks out there - a tip on keeping things organized by using git submodules for package management.



With CodeIgniter moving to GitHub we are starting to see a lot of CodeIgniter developers wanting to learn more about Git, specifically how they can use it to improve their workflows, manage their applications and move away from the horrible days of copying and pasting updated libraries off a wiki. UCK. Sparks are helping us on the whole, but there is another method that we can use to manage our packages: Git Submodules.


Submodules allow you to pull in source from a remote repository without having to merge the code into your own. It creates a dependency between the two and makes it easier to check out only what you need. He gives the example of his oauth2 package being needed in multiple other applications, so instead of including and checking in multiple versions, he made a separate repo and defined the source as a submodule. He also includes a bit about fixing issues in your submodules with a few handy commands to get on the right branch, add a remote and push the commit.

Josh Adell's Blog: Phar Flung Phing


Josh Adell has posted about a bit of automation he set up with Phing and PHP's phar packaging to create an archive as a part of his build system. It's a simple five step process mad even easier by the fact that Phing already has a PharPackage task.



One of the cooler features of PHP 5.3 is the ability to package up a set of PHP class files and scripts into a single archive, known as a PHAR ("PHp ARchive"). [...] I decided to see how easy it would be to wrap up Neo4jPHP in a PHAR for distribution. [...] Since I also started playing with Phing recently, I decided to see if I could incorporate packaging a project as a PHAR into my build system. It turns out, it's pretty easy, given that Phing has a built-in PharPackage task.


He points you towards Phing's PEAR channel to get the tool installed and includes a command-line call to update your php.ini to allow PHP to generate phar files. Code is included to create the phar-generation stub as well as the XML for the Phing build file. You can find his end result here.

2011年9月23日星期五

Site News: Popular Posts for the Week of 09.23.2011

Popular posts from PHPDeveloper.org for the past week:

King Foo Blog: Using Complex Type with Zend_Soap


New from the King Foo blog there's a tutorial showing how to use complex types in a SOAP request with Zend_Soap, a component of the Zend Framework.



To be able to use complex types with Soap requests, they need to be fully defined in the WSDL file. Zend_Soap can automate this process, if you know how to define those complex types. Let us start without it Zend_Soap's magic and compare it with a fully discovered complex request type afterwards.


In their example, they have a collection of books (objects) that they want to send over to the web service. The code for both the server and client side are included with the WSDL automagically created by the Zend_Soap_Server component. By setting docblock comments on the properties of the Book objects, the SOAP components automatically know what types they are. Their example defines these, and sets up the web service on the other side with a classmap to define where the "tags" information for each book lies.

Derick Rethans' Blog: Xdebug's Code Coverage speedup


Derick Rethans has a new post to his blog today talking about some work that's been done to speed up XDebug's code coverage generation. Changes in the coming 2.2 release have some improvements that make things perform better and put less stress on PHP in the process.



Code coverage tells you how much of your code base is actually being tested by your unit tests. It's a very useful feature, but sadly, it slows down PHP's execution quite a lot. One part of this slowdown is the overhead to record the information internally, but another part is because I have to overload lots of opcodes. (Opcodes are PHP's internal execution units, similar to assembler instructions) They are always overloaded even if code coverage is not used, because it's only safe to overload them for the whole request.


These changes were from a combination of contributions from Taavi Burns and a new ini setting that will allow you to enable or disable the code coverage in XDebug. Benchmarking shows a good amount of time reduction in coverage runs - dropping anywhere from a few seconds to over a minute. He also mentions the idea of "modes", shortcuts to predefined settings for different types of reporting (like "profiling" or "tracing").

Gareth Heyes' Blog: Non alphanumeric code in PHP


Gareth Heyes has tried out an interesting experiment - running non-alphanumeric code in PHP using only octal escapes.



So a small php shell was tweeted around and it inspired me to investigate a way to execute non-alphanumeric code. First off I started with the idea of using octal escapes in PHP and constructing the escape so for example: 107 is "G" if I could construct the "107" and add the backslash to the beginning maybe I could construct "G".


A snippet of example code is included showing his octal-based code for creating a "G" (6 lines of pluses, parentheses, equals and a few more characters). By doing some trickery with bitwise operators on strings, he was able to combine characters and make the string "GET". Pretty clever, even if it's not entirely practical.

2011年9月22日星期四

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

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

PHPMaster.com: From Zero to Cloud: Setting up an EC2 Sandbox, Part 3


SitePoint's PHPMaster has a new post today, the third part of a series helping you get your application from "zero to cloud" on an Amazon EC2 setup. In this latest post they wrap things up by showing how to set up the full lamp stack on the remote server. Here's part one and two that lead up to this latest part.



This is the final article in a three part series focused on setting up EC2 as a sandbox for application developers. I assume you have an AWS account with Amazon; if you don't, please read Part 1 to learn how easy it is to sign up. I also assume you have configured your development environment and installed an AMI; if you haven't, please read Part 2. In this installment, we'll learn how to install Apache, MySQL and PHP in our running AMI, and then clone the AMI to make our own.


Included in the post are all the commands you'll need to get the packages installed for PHP, MySQL, Apache 2, PEAR and the PHP command line binary. With all of that installed, they show you how to create an AMI (Amazon Machine Image) to make it easier to scale in the future.

XpertDeveloper.com: PHP clearstatecache() Explained


XPertDeveloper.com has a quick new post looking at a function that might be overlooked until it suddenly becomes just what you need - clearstatecache for clearing file state information in the current script.



For the functions like is_file(), file_exists(), etc PHP caches the result of this function for each file for faster performance if function called again. But in some cases you want to clear this cached information, for the task like getting the information of the same file multiple times in same page.


Other methods this cache effects include stat, file_exists, is_file and more. If the state of a file is changed during the course of the script - say it's deleted manually, not by PHP, your script may not recognize that. By calling clearstatecache, you refresh this cache and make it possible to see the latest file system info.

PHPBuilder.com: Introducing Namespaces for PHP Developers


On PHPBuilder.com today there's a new article from Jason Gilmore introducing you to namespaces in PHP 5.3+ development. Namespaces make it simpler to separate out your code into functional pieces and help keep it organized.



The inclusion of namespace support within PHP 5.3 effectively brought the need for gripes and workarounds to a halt, however adoption of this exciting new feature has seemed surprisingly slow in the more than two years since its release. [...] The utility of this new feature is simply undeniable. Therefore I thought it would be worthwhile to offer a formal introduction to namespaces for the benefit of those PHP developers who haven't yet had the opportunity to investigate the topic.


He starts by introducing the concept of a "namespace" as a sort of container for your code, providing separation that prevents errors like the infamous "cannot redeclare class" issue. He includes examples of PHP's namespace syntax to split out two "Account" classes into two different sections. Using them is as easy as referring to them by their namespaced "path" or using something like the "use" keyword to reassign it to another name.

2011年9月21日星期三

Community News: Latest Releases from PHPClasses.org

DZone.com: Practical Google+ Api


On Dzone.com today Giorgio Sironi has a new post looking at a relatively new release on the social networking scene for developers, the Google+ Api, and some details on how you get get started writing apps using the features it offers.



Google+ recently releases to developers the first version of its Api, which focuses on public data about profiles and their activities: status updates, resharings and links. I dived into the Api and wrote a small sample application to get a feel of how easy is to get started, and what can we do with the Api for now. All the code is at the bottom of this post.


He goes through the steps you'll need to get set up - registering an application, getting a library to help make the connection (here's a PHP one) and configuring it with your credentials. You can get "People" and "Activities" information from the API. He shows some sample output for each - basic user information (nested arrays) and some of his activities (again, nested arrays). He includes the source for his sample application that pulls a user's profile information and lists out their latest (public) activities.

Alberto Viana's Blog: Zend Framework and Oracle XMLType


Alberto Viana has a new post to his blog about using Oracle ZML Types with a Zend Framework application. He created a custom adapter to create the type and handle the binding/execution on an new OCI8 connection.



So few days ago I needed to insert Oracle XMLtype with Zend Framework. I used oracle adapter to wrote it in Zend Framework. I was looking for and I found on Chris Jones Blog.


His table has a column defined as an XMLType, a special data type specifically for working with XML datasets directly in the database. His adapter includes a bit of sample XML and the code needed to bind the data as a CLOB and, using the writeTemporary function.

Ibuildings techPortal: DPC Radio: Let's take over the world with Zend Framework


On the Ibuildings techPortal today they've posted the latest episode in their DPC Radio series as recorded at last year's Dutch PHP Conference. This episode is Martin de Keijzer's talk Let's take over the world with Zend Framework.



Many people use Zend Framework for it's MVC implementation, but it has a lot of hidden gems. Internationalization (i18n) is one of them. We will look how you can create an application that will have the right languages, currencies, dates and times all based on the location of the visiting user. This session will take away a lot of headaches in international projects and will improve the quality in overall.


To listen you can either use the in-page player, download the mp3 or subscribe to their feed to get the latest. Martin's slides are also posted to Slideshare.

2011年9月20日星期二

Community News: Latest PECL Releases for 09.20.2011

Latest PECL Releases:

PHPMaster.com: Introduction to PHP Arrays


On the PHPMaster.com site today, there's a good introduction to a basic data type in PHP - working with arrays. This tutorial is a low level look at what arrays are and how to work with them (briefly).



Tables organize data in such a way that we can easily find correlations or perform straightforward computations. A array is essentially a way to organize data in a table-like manner. The name "array" comes from the same Latin roots as the word "arrangement."


If you're anything other than completely new to the language, this post won't help you much. If you're new to programming, though, learning about arrays in PHP is key to your budding development skills. For more in-depth looks at using arrays, checkout these results.

Ralph Schindler's Blog: Autoloading (Revisited)


Ralph Schindler has a new post to his today looking back at a sort of history of autoloading and some of what we've learned even in just the journey from PHP 5.0 to 5.3 (and has become best practice in the community).



It wasn't until years later that certain best practices had emerged and the prolific usage of require_once/include_once throughout large bodies of code had started drying up. Even after autoloading had been adopted by larger more visible projects, a common patten had yet to emerge. [...] Fast-forward to today, and we see that this standard for autoloading has agreed upon by a large number of projects and has come to be named the "PSR-0 autoloading standard".


He covers some of the things we (the development community) have learned about autoloading and resources in our applications. He talks about the classmap tool that Matthew Weier O'Phinney developed (and some of its downfalls) as well as a move into PHP namespacing that has helped to make some of the "namespacing" based on class names obsolete. He's noticed a pattern in namespacing already - a self-contained structure that provides more of a "drop in" solution and how that's handled in the code.

2011年9月19日星期一

Community News: Latest PEAR Releases for 09.19.2011

Latest PEAR Releases:

Phil Sturgeon's Blog: NinjAuth: The Social Integration Package PHP has been dying for


New on his blog Phil Sturgeon has a post about the social integration package PHP has been dying for - NinjAuth. It has hooks for OAuth and OAuth2 connections and makes it simple to use them completely abstracted.



In the past I have never needed to implement oAuth into a PHP project. I have done it in Rails and boy it was easy thanks to OmniAuth. OmniAuth abstracts away so much of the grunt work that it takes about 5 minutes to add a new social network to your site, and 4 of those minutes are spent signing up for the API keys. What options do we have in the world of PHP? A bunch of screwy hacks or provider specific classes like TwitterOAuth. I don't want to hunt down 20 libraries with different methods, I want to get a key, bang it in and go to the pub. Well, now I can!


The NinjaAuth system allows a user to have multiple "authentications" groups under it corresponding to various social networking sites. It uses the fuel-oauth and fuel-oauth2 packages to drive its backend. He includes a code snippet showing how to configure the providers (complete with keys needed for auth) including Facebook, Flickr, GitHub, YouTube and - of course - Twitter. You can grab the latest version of this library from Phil's github account.

Håvard Eide's Blog: ChaosMonkey


Håvard Eide has a new post sharing a tool he's created (based on some ideas presented in this netflix blog post) for testing a web service. Specifically, his tool helps you test a web service developed with the Slim framework.



I just pushed a example on how to create a ChaosMonkey with the Slim framework to github. The idea is that whenever you create a webservice with the Slim framework (which is really simple) you rarely test for failure, the ChaosMonkey class will help you to do just that. When initialized with the AbsoluteChaos plugin it will randomly kill the webservice with exceptions, garbage to the output, or just run the service for you without failure at all.


His plugin does a lot of things right now, but it's easy to extend with your own failure types - like his suggested "networkSleep" or something that could kill the connection to MySQL. He includes a code snippet in the post of how to hook Slim and ChaosMonkey together for some testing fun.

2011年9月16日星期五

Site News: Popular Posts for the Week of 09.16.2011

Popular posts from PHPDeveloper.org for the past week:

XPertDeveloper.com: PHP Debugging Tools


On the XPertDeveloper.com blog today there's a new post sharing four handy debugging tools you can use to make finding those elusive problems in your code simpler.



PHP is very well used scripting language in now a days. But PHP does not have any inbuilt debugging tools or extension. But we have some extensions and tools available which serves the debugging purpose of the PHP.

The tools on their list involve both the backend and frontend:


Lorna Mitchell's Blog: ArrayAccess vs ArrayObject


Lorna Mitchell has a new post to her blog explaining ArrayObject and ArrayAccess and how each is used.



I help people qualify for Zend Certification and in the last few months I've had questions about both ArrayAccess and ArrayObject. This post is an attempt to illuminate both. In very simple terms, ArrayAccess is an interface, which you can implement in your own objects; ArrayObject, on the other hand, is a class, which you can either use or extend.


She give an example of ArrayAccess - a simple class that implements it to make it work like an array. For ArrayObject, she describes some of the things it comes with, including automatically implementing the ArrayAccess, Countable and Traversable interfaces making it a "more powerful array" type.

Michael Nitschinger's Blog: Quick Tip: Lithium Redirect


Michael Nitschinger has a "quick tip" posted in this new entry to his blog - how to handle a redirect in a Lithium-framework based application.



While migrating pastium over to MongoDB (from CouchDB), I found [a] snippet in the routes.php file [that makes it so] when the user enters the application via the root url (/), he instantly gets redirected to /pastes/add (or a different URL if you have custom routes configured). This may seem ok at first, but there's a problem. It doesn't take URLs into account that don't live directly under the document root.


The snippet he references and others showing how to correct the issue are included - replacing the location array controller/action information with the static class information for the route in a match() call. For more information on the routing in Lithium, see these manual pages.

2011年9月15日星期四

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

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

Script-Tutorials.com: How to Use APC Caching with PHP


On Script-Tutorials.com today there's a new article introducing you to using APC caching in your PHP applications. Their simple example sets up a caching class that handles the dirty work for you.



Today I have another interesting article for PHP. We will talking about caching, and practice of using caching in php. I will make review of APC caching and will show you how you can use APC in PHP. [...] Now people have learned to use the server memory for data storage. RAM much faster than hard disk, and the price of memory falls all the time, so let's use all these advantages of this.


Included in the post is the code for a few different files - the caching class itself that implements the APC functions in PHP and some examples of it in use: saving objects, fetching data from the cache and removing things from the cache.

ProDevTips.com: MySQL replication in PHP - on the same machine


ProDevTips.com has a new tutorial posted today sharing a database replication script they've put together to keep two databases in sync.



After reading up on MySQL replication for a bit I realized that it would go quicker to simply write something in PHP that would sync a subset of tables in one database to exact copies of the same tables in another. Note that the code/SQL [in the example] only works if you replicate from one database to another on the same machine since the main thing here are SQL queries that contain operations/look ups on two databases in the same query.


He includes the code to do the fetch on certain tables (based on a unique key), pushes them into an array and exports them back out into another table. There's also a modification included that makes it work on tables without an auto-increment column.

Community News: SitePoint Launches PHPMaster.com


The crew over at SitePoint have introduced a new PHP-specific resource that's looking to provide a good resource for those looking for community info and tutorials - PHPMaster.com.



PHPMaster is the latest and greatest in the SitePoint family, dedicated to bringing you the highest quality in tutorials from some of the web's best PHP Developers, as well as news and information on events in the PHP Community.

Tutorials posted so far include:


2011年9月14日星期三

Community News: Latest Releases from PHPClasses.org

Marco Tabini's Blog: Suggestions for a younger developer


In a new post to his blog Marco Tabini offers some quick advice to younger developers looking to make their mark in their profession (PHP-related or not). He shares five tips to keep in mind as you hone your process and write your code.


Every now and then, I get asked by developers who are just getting started in the trade if I have any suggestions to help them out - favourite language, tips and tricks, and the like. None of these things matter, really, but there are a few things I wish I had known when I started out that have nothing to do with the mechanics of software development.

His tips each come with a paragraph or so of explanation:



  • Be humble
  • There is no magic
  • Programming is a craft, not an art
  • Software solves problems
  • Code doesn't leave sawdust

Lars Tesmer's Blog: Learning Ruby: Gotchas and Pitfalls for PHP Programmers


Lars Tesmer is currently in the process of learning Ruby. He' been working through the tutorials and some sample scripts and has come across some pitfalls along the way. In his latest post he shares four of them that've stood out in his development so far.



I'm currently learning Ruby. In this post I'll list some pitfalls for programmers coming from PHP that would probably cause some confusion if you aren't aware of them. This list is by no means complete, while I learn Ruby I'll very probably encounter more gotchas, which I will blog about, too.


For each of his four examples, he gives the code PHP developers are used to seeing and the Ruby code that may or may not do what you'd expect:



  • Arrays are continuous
  • Zero is not falsy
  • The keywords private and protected
  • There's no static keyword

Kevin Schroeder's Blog: ZendCon 2010 Podcasts


Kevin Schroeder has a new post to his blog today with a huge list of podcasts for your listening pleasure - the complete list of ZendCon 2010 sessions as recorded at last year's event.



I've decided to [...] just upload them all so that you can download them all in preparation for this year's ZendCon. As you listen to these paragons of PHP goodness think of how wonderful it would be for you to be there in person and talk to these founts of wisdom. You will find several of the speakers from last year at ZendCon as well as a bunch of new ones. While you may have missed the early registration there is still time for you to get your tickets to ZendCon 2011.


There's about 75 of them for you to enjoy and not much time for you to catch up - this year's ZendCon happens in October (17th-21st) in Santa Clara, CA. They have a great list of sessions for this year's event too (which I'm sure will all be recorded for release next year as well)!

2011年9月13日星期二

Community News: Latest PECL Releases for 09.13.2011

Latest PECL Releases:

Sameer Borate's Blog: Functional programming with Underscore.php


In a new post to his blog Sameer Borate looks at using the Underscore.php library to do a little functional programming in PHP. Underscrore.phpis a PHP port of Underscrore.js.



Underscore.php provides a utility library for PHP that provides a lot of the functional programming support that a programmer would expect in Ruby, but without adding much overhead during execution. The only caveat is that underscore.php requires PHP 5.3 or greater. Although you could accomplish some of the things using PHP's built in functions, the functional approach looks intuitive and easy to work with.


He gives a few simple code examples - one using the "pluck" method to pull certain values out of an array, the "map" method to apply a transformation to each item in an array and some OOP examples showing the use of the "max" and "template" methods.

Matthew Weier O'Phinney's Blog: Using the ZF2 EventManager


Matthew Weier O'Phinney, lead on the Zend Framework project, has a new post to his blog talking about the event manager in the Zend Framework, v2 and how to use it in a refectored version of a previous post.



Earlier this year, I wrote about Aspects, Intercepting Filters, Signal Slots, and Events, in order to compare these similar approaches to handling both asychronous programming as well as handling cross-cutting application concerns in a cohesive way. I took the research I did for that article, and applied it to what was then a "SignalSlot" implementation within Zend Framework 2, and refactored that work into a new "EventManager" component. This article is intended to get you up and running with it.


You'll need to already have an install of the Zend Framework (v2) installed to follow along. He covers some of the basic terminology and the base code the rest of the tutorial's built from - a simple EventManager instance with a trigger on it. He moves on from there showing how to specify targets for the triggers, setting up global static listeners and listener aggregates as well as how to short circuit listener execution. He wraps up the post by applying all of the examples into one simple caching tool that responds to the trigger by either sending back a new instance or pulling the previously generated one from the cache.

2011年9月12日星期一

Community News: Latest PEAR Releases for 09.12.2011

Latest PEAR Releases:

SitePoint Podcast: #129: Taking PHP to the Next Level with Lorna Mitchell


On the SitePoint podcast, there's a new episode with Lorna Mitchell where she and host Louis Simoneau talk about taking your PHP to the next level, some of her work in Open Source and her involvement in their upcoming advanced PHP book.



Episode 129 of The SitePoint Podcast is now available! This week our regular interview host Louis Simoneau (@rssaddict) interviews Lorna Mitchell (@Lornajane) one of a team of 3 co-authors working on an upcoming release for SitePoint, an advanced book on PHP.


You can either listen to this latest episode using the in-page player or by downloading the mp3 directly. Of course, you can always subscribe to their podcast feed and get this and other new shows as they're released.

Federico Cargnelutti's Blog: Building a RESTful Web API with PHP and Apify


Federico Cargnelutt has a new post to his blog showing you how to create a REST API for your site using the Apify (complete with a shiny new 1.0 release).



Web services are a great way to extend your web application, however, adding a web API to an existing web application can be a tedious and time-consuming task. Apify takes certain common patterns found in most web services and abstracts them so that you can quickly write web APIs without having to write too much code.


Some code snippets are included to build a simple REST service - first some examples with user handling then a more fleshed out example of a controller that lets you fetch "post" information as pulled from a model. A screencast has also been posted showing the library in action.

Juozas Kaziukenas' Blog: Dependencies management in PHP projects


In his latest post to his Web Species blog Juozas Kaziukenas looks at dependency management in PHP applications and offers a few suggestions of how you can make them easier to track.



Rarely a project lives by itself, especially in the days of frameworks. Furthermore, there are a lot of great open source libraries you might want to use to save time. But all of this raises a new problem - how could we manage all those dependencies. Here are some thoughts on this problem and how you might want to solve it; without shooting yourself in a foot.


He mentions svn:externals and git's submodule as options in version control systems, PEAR for package management, Apache Maven and the deps file in the Symfony framework.

2011年9月9日星期五

Site News: Popular Posts for the Week of 09.09.2011

Popular posts from PHPDeveloper.org for the past week:

Kevin Schroeder's Blog: Why PHP?


Kevin Schroeder has a new post to his blog today asking "Why PHP?" - not so much a "why you should chose PHP for your development", more of a why PHP is the way it is.



Today on twitter there was a conversation going on about the responsiveness of the core PHP developers to PHP users. [...] This post isn't necessarily to correct perceived errors, to stand behind correct statements, or to state what I believe the problem is. Rather, it is to add something to the conversation that I don't think I've seen much of. The Twitter conversation was, for me, more of a contemplation kickoff and so the purpose of this post is to propose some thoughts for consideration. I don't have sufficient karma to propose changes directly, but I have bet my career on PHP and I want to see it beat the crap out of every language out there.


He points out that most of the opinions out there seem to be of the "what" PHP is rather than the "why" PHP is. He notes that the discussions about the core development (and developers) that's been happening recently is more of a symptom of a larger problem - an unclear definition as to what PHP is and what problem it's there to solve.

Marco Tabini's Blog: The easiest way to add unit test to your application


In a new post to his blog Marco Tabini offers some suggestions on unit testing - not really a tutorial on how to it, more of an "easy way in" to introducing it to your development process.



Stopping development for weeks while you figure out how to add unit tests to cover your entire codebase is simply something that cannot be done (at least, not if you want to keep your job), no matter what future benefits it might bring. The good news is, adding unit testing to your existing project only takes five minutes - which is pretty much how long it takes to get a unit testing framework installed. That's it. Move on.


He puts the emphasis on unit testing to manage change in a code base, not so much to ensure that the current application runs as it should (not initially at least). He's found them most useful in bugfixing, refactoring and when adding new functionality. Current tests (and even tests written in TDD) can help with all of these. He includes reminders that if the tests aren't written well, they're useless and that once you've started testing, it needs to be continuous, even if they're not perfect.

2011年9月8日星期四

Community News: PHP version control to move to git


A little while back, the PHP development group posted a survey of developers asking them which version control system they'd like to see the PHP project use. By an overwhelming margin, git has won and things are already in motion to move parts of the project away from subversion.


In his mailing list post, David Soria Parra explains:



After 2 weeks of voting and discussion, I closed the votes today. The results are fairly straightforward. Most of the users want to move to a decentralized version control system. [...] I don't want to make a difference of who voted for what. I think the results are overwhelming
in favor of Git.


He'll be working on the spec to make the move for the PHP source over to git and is planning a cut over some time in December. Stay tuned to the php.internals mailing list for more details about the move as they come up.

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

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

Joe Devon's Blog: How to get your talk accepted, experiences on the advisory board of Semtech & Zend


As a result of the ZendCon advisory board for this year's event, Joe Devon has posted a guide that wants to help you get your talks accepted to conferences in the future (both PHP-related and not).



For those who don't know what an advisory board is, conference organizers get loads of proposals and need help deciding who should speak. So they ask others in the industry to provide some feedback. It was quite a learning experience.


He talks some about the "speaker backlash" that comes from being rejected, a lack of professionalism in some submittors and some basic (common sense) recommendations like:



  • fill out the form completely, even if you don't think it's all useful
  • start locally and then move up. A major conference isn't the place to try out your speaking first-shot
  • whet the board's appetite - make them want to hear more about the topic or come up with something new
  • share your unique experience with the technology
  • use sites like Joind.in, Meetup and SlideShare to your advantage

Jakub Zalas' Blog: Managing object creation in PHP with the Symfony2 Dependency Injection component


On his blog today Jakub Zalas has posted a tutorial he's written up about using dependency injection in PHP with the Symfony2 dependency injection component (DIC).



Symfony's DependencyInjection component is a PHP implementation of a Service Container, or as others like to call it, a Dependency Injection Container (DIC). The component also provides useful tools for handling service definitions, like XML loaders or dumpers. If you want to learn more about the dependency injection or the dependency injection container, read an excellent series of articles on the subject by Fabien Potencier: What is Dependency Injection?


He walks you through the entire process - installing the needed libraries (the DIC, a config and class loader component and Buzz, a lightweight HTTP client). Code is included to show object creation the "usual way" and then creating the same types of objects in a dependency injection environment. Also included is a sample XML document describing the services for the container. He finishes the post with a GraphvizDumper-generated image for the container.

PHPBuilder.com: PHP Simple HTML DOM Parser: Editing HTML Elements in PHP


On PHPBuilder.com today there's a new tutorial from Vojislav Janjic about using a simple DOM parser in PHP to edit the markup even if it's not correctly W3C-formatted - the Simple HTML DOM Parser



Simple HTML DOM parser is a PHP 5+ class which helps you manipulate HTML elements. The class is not limited to valid HTML; it can also work with HTML code that did not pass W3C validation. Document objects can be found using selectors, similar to those in jQuery. You can find elements by ids, classes, tags, and much more. DOM elements can also be added, deleted or altered.


They help you get started using the parser, passing in the HTML content to be handled (either directly via a string or loading a file) and locating elements in the document either by ID, class or tag. Selectors similar to those in CSS are available. Finally, they show how to find an object and update its contents, either by adding more HTML inside or by appending a new object after it.

2011年9月7日星期三

Community News: Latest Releases from PHPClasses.org

Community News: ZendCon Early Bird Pricing Deadline Coming Soon


The folks over at Zend would like to remind you that the deadline for Early Bird pricing on ZendCon conference tickets is coming soon - September 16th!



The Zend PHP Conference (ZendCon) will be held October 17-20, 2011, at the Convention Center in Santa Clara, California. [...] The conference opening keynote will be given by Andi Gutmans, CEO and co-founder of Zend, who will be joined onstage by Michael Crandell, CEO and co-founder of RightScale.


Other keynotes include ones from Jeff Barr (Amazon), Hugh Williams (eBay) and Dwight Merriman (founder of 10gen). You an find out more about these sessions and lots of others packed into this great multi-day conference over on the ZendCon site. Register now to get the Early Bird pricing ($200 USD off the regular ticket price for the full event).

Sameer Borate's Blog: Microsoft Bing Translation PHP wrapper


In a new post to his blog today Sameer Borate spotlights a translation wrapper for Bing that lets you easily use their API to translate text or determine what language the given text is in.



Microsoft Language translation is an interesting service. Not only can you do language translation, you can also detect the language of a particular text. The given class provides a PHP wrapper which will help developers translate text from one language to another in a easy manner. The library also supports caching, helping you keep your translations fast and simple.


His translation library requires an AppId for configuration and cURL to handle the messaging back and forth. Translation is as easy as calling "translate()" on a string, language fetching with "LanguageNames()" and even converting the text to speech with the "speak()" method.

DZone.com: CakePHP - Web Test Cases with SimpleTest


On DZone.com today there's a new post written up by Mike Bernat about making web test cases for CakePHP applications with SimpleTest.



Most of the applications I work on have very straight-forward components and not a lot of complex functions/methods. I would only be testing whether or not they worked at all, rather than if they worked in a wide-array of situations. [...] For example, unit-testing a simple news list and detail page is probably overkill. Sure, you can test your classes by simple instantiating them but that only goes so far. My new method involves using SimpleTest's Scriptable Browser to actually crawl webpages and ensure that the proper data is being displayed.


He includes a few snippets of code to show how to implement SimpleTest's web test functionality - one that just checks a HTTP response values, another that checks for text on the page, one testing for a login on an admin page and a test for add/edit pages to ensure valid loading based on URLs/links.

2011年9月6日星期二

Community News: Latest PECL Releases for 09.06.2011

Latest PECL Releases:

Community News: ConFoo 2012 Call for Papers Extended


The ConFoo conference has announced that their Call for Papers has been extended until September 16th for this years event happening February 29th through March 2nd.



Many of you are just back from vacation. because of that, we decided to extend the call for papers until September 16. For speakers, that means more time to prepare abstracts. For everyone else, it's more time to read the proposals and cast your vote.


You can find out more information about the ConFoo Call for Papers in their site. They're looking for topics ranging from Java, Ruby and Javascript out to Web Standards, Project Management and Agile methods. If you'd like to submit papers, you can head to their submission form or you can rate other proposals.

NetTuts.com: Rapid Application Prototyping in PHP Using a Micro Framework


On NetTuts.com today there's a new tutorial posted about using a microframework for prototyping an application you may not need a full stack framework to get running. Their examples are based on the Slim framework.



Let's face it: we all have great ideas for a web application. Whether you write them down on paper or remember them using your eidetic memory, there comes a point when you want test whether or not your idea is really viable. In this tutorial, we'll use a micro framework, a templating language and an ORM to rapidly develop an application prototype.


There's an introduction to help you get Slim, some extras, Twig templating and Paris and Idorm set up and working happily together. There's code included for bootstrapping the application, creating a few routes, building models and using them to pull data from the database. They also create an "admin" area for their sample blog application, building an "add article" form and protecting it with a simple login system. You can download the source if you'd like to see it all working together.

Christian Weiske's Blog: phpfarm moved to SourceForge


Christian Weiske has a new post about a move the phpfarm tool has made over to SourceForge for its project page. phpfarm makes it simple to switch between multiple versions of PHP on the same server to make debugging and development a much simpler task (especially if you're not in a homogeneous environment).



phpfarm, the tool that lets you install multiple PHP versions beside each other, finally got a proper project page on SourceForge. By moving from svn.php.net to SF, phpfarm got a nice git repository, a wiki and a ticketing system. It also has a Phing build file now which generates and uploads release files, so people don't have to install git to get phpfarm.


His post also includes some of the changes made in the latest release (0.1.0) and how you can clone the code from the SF.net repository.

2011年9月5日星期一

Community News: Latest PEAR Releases for 09.05.2011

Latest PEAR Releases:

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


Michelangelo van Dam has posted the fourth part of his "Quality Assurance in PHP projects" series to his blog today - a continuation of his emphasis on PHPUnit and testing his sample "Tic-Tac-Toe" game.



In parts one, two and three we focussed on writing tests for a game of tic-tac-toe, with in parts two and three we optimized our tests so they focus on the functionality of the individual parts Grid and Player, with a collection class Players to handle Player objects.


In this fourth part he focuses on the rules for playing the game and the unit tests to validate the correct flow. He covers one of his tests before, looking at the "can be played" validation for identical symbols. He modifies this to use a provider that gives the test the set of data to work from with varying symbols. He writes additional tests to be sure the game "stops after winning" and that it has a winner/which player is the winner. You can find the full game source (complete with these tests) on his github account.

James Morris' Blog: A Symfony2 Console Command and the Foursquare API Venuehistory


In a new post to his blog James Morris has shared a custom Symfony2 console command he's written to pull in Foursquare data for his testing locally.



I've been playing with the Foursquare API recently, I'm attempting to get a new homepage built and want to display a map of where I hang out. I use Foursquare quite a bit so wanted to get the locations from their API then plot them on Google maps. There's a venuehistory endpoint that gives you a massive list of all the venues you've checked into with details such as the venue name, location including lat and lng coordinates, and the count of times you've checked in.


He includes a screenshot of the API's results, the code you'll need to recreate it and an example of it running.

Lars Tesmer's Blog: PHPUnit: Better Syntax for Expecting Exceptions


Lars Tesmer has an alternative to testing xceptions in PHPUnit that's a bit more flexible than just a docblock comment definition.



My main issues with this way of expecting exceptions are:

The expectation is pretty far away from the location you'd normally expect to find an assertion. Usually, an assertion can be found at the bottom of each test function, whereas with the current method PHPUnit uses, it's at the top of the test-function. Additionally, it's an annotation "buried" in a comment which is easy to miss. Finally, PHPUnit will watch for an exception thrown by any of the code inside the test-function.


To replace it, he's created an "assertThrowsException" test that takes in the exception type to test for and the code to test for the exception (via a closure). He has his proof-of-concept posted on github if you'd like to give it a try. This also allows you to test for more than one exception in the same test, possibly as a result of slightly different conditions.

2011年9月2日星期五

Site News: Popular Posts for the Week of 09.02.2011

Popular posts from PHPDeveloper.org for the past week:

CodeIgniter.com: Amazing Progress Report & Addition of IRC to CodeIgniter.com


On CodeIgniter.com there's a new post updating the community on more of the current happenings surrounding the project including the status of their move to github and another source for developers to find the CI help they need.




In less than two weeks since the announcement was made at CICON that CodeIgniter was moving to GitHub, we've seen some incredible results from the change. Already CodeIgniter is the 10th most watched PHP project at GitHub (currently 758), with 42 open pull requests, 53 merged pull requests, 170 forks, and 41 individual contributors. Incredible!



[...] We also noticed what seemed to be a spike in activity on the #CodeIgniter Freenode IRC channel, so we've decided to make it more prominent to encourage its continued use. You'll now notice an IRC tab in the main navigation, letting you access the #CodeIgniter IRC channel right here at CodeIgniter.com.




If you want more details on why they made the switch over to git, check out this blog entry from the EllisLab site for an explanation from Derek Jones

Brian Moon's Blog: Check for a TTY or interactive terminal in PHP


In a new post to his blog Brian Moon describes a need he had for detecting if the client or user calling a PHP script was using an interactive terminal (TTY) or not:



Let's say I am trying to find out why some file import did not happen. Running the job that is supposed to do it may yield an error. Maybe it was a file permission issue or something. There are other people watching the alerts. What they don't know is that I am running the code and looking at these errors in real time.


Since the errors were being sent to the log file, they were lost to the client/user on the other end left staring at their script wondering what went wrong. He ended up with a solution (a pretty simple one too) that uses posix_ttyname and posix_isatty. He includes the little snippet of code he puts in his prepend file that checks for errors then checks for a TTY. If both are there, it turns off logging the errors to the file and sends them direct instead.

2011年9月1日星期四

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

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

Court Ewing's Blog: How PHP is Broken and How It Can Be Fixed


Court Ewing has a (slightly inflammatory) post to his blog that shares some of his opinions on why he thinks PHP is broken and a few thoughts on how it could be fixed. He's edited the article since its first publishing to include some clarification of his original ideas.



Before getting into the original post, I wanted to a comment made in his edit with an apology for the original post coming across as more of an "irritated user" than an unopinionated observer.



PHP's development process has been broken for a long time, and the failures of that process have swelled since the first ripples began to appear many years ago. [...] This is no surprise given the very fluid history of PHP though, and the lack of any sustainable processes may have even been one of the key things that allowed PHP to evolve so quickly into one of the most used programming languages in the world. But that early success doesn't make the PHP development process any less broken.


He covers a few points where he has issues with the PHP project including the release management, test coverage and recent issues with bugs in releases. He gives suggestions on how things could be made better - a detailed release process, a voting process for new features and a emphasis on good code and tests in the core. He also notes that he thinks more contributors in the mix isn't the solution. While it's encouraged to join the project, he suggests that the current core development group are the ones that should work the hardest on making things better.



Be sure to check out the comments for some great responses from the PHP community - both for and against the statements from the original post.

PHPBuilder.com: Building a Multilingual PHP Website


On PHPBuilder.com today there's a new post from Vojislav Janjic with three methods (sans-framework) that you can use to create a multilingual website - some a bit easier to maintain than others.



Fast internet growth has brought many opportunities in the global market. Businesses can reach their customers across many countries, and information sharing is not limited to a local area or country anymore. This is why there is an increasing tendency for multilingual websites. By having a website in multiple languages, you can target local markets more easily. Also, it is more convenient to use a website in your native language.


His three methods are all relatively simple, but they all have their good and bad points - making separate HTML/views for each language, creating XML files with different versions of the content or storing the translations in a MySQL database. He gives quick code snippets showing how to implement each of them, some basing the language on a cookie value, others on a GET variable passed to the page.