100722 items (110 unread) in 22 feeds
MSNBC
(1 unread)
PHP
(61 unread)
Deals
(12 unread)
Web Development
(35 unread)
CNN Money
(1 unread)
A leap day with a post on Date/Time issues seems fitting...
Earlier today, on twitter, @skoop asked: "dear #lazyweb, when I use DateTimeZone('GMT'), why does format('e') output UTC?" What he means is that:
$date = new DateTime('now', new DateTimeZone('GMT'));
echo $date->format(DateTime::RFC2822 . ' e' );
which shows:
Wed, 29 Feb 2012 16:26:23 +0000 UTC
As you can see that has UTC and not GMT as you might expect.
If you look closely at the documentation for the "Other" group of timezones, it lists with the GMT timezone as warning: "Please do not use any of the timezones listed here (besides UTC), they only exist for backward compatible reasons." If you use GMT as timezone identifier in the constructor to DateTimeZone, PHP will instead use the correct UTC in output. When you create a DateTimeZone object like this, you will always get a "type 3" DateTimeZone object:
$date = new DateTime('now', new DateTimeZone('GMT'));
var_dump($date);
which shows:
object(DateTime)#1 (3) {
["date"]=>
string(19) "2012-02-29 16:30:51"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}
Now apparently some systems *cough*Silverlight*cough* require GMT to be used. GMT is not a timezone, but just a timezone abbreviation meant for output only. Read more about that in the article "Leap Seconds and What To Do With Them". However, if it is necessary you can create a DateTime object with a different timezone type. In this case you want a "type 2" timezone associated with the DateTime object. You do that by simply forcing that timezone abbreviation when instantiating a DateTime object:
$date = new DateTime('today GMT');
var_dump( $date );
which shows:
object(DateTime)#1 (3) {
["date"]=>
string(19) "2012-02-29 16:32:16"
["timezone_type"]=>
int(2)
["timezone"]=>
string(3) "GMT"
}
Things like this also work:
$date = new DateTime( "GMT" ); $date->setDate( 2012, 2, 19 ); var_dump( $date );
And of course, this is not limited to GMT only:
$date = new DateTime( "EST" ); $date->setDate( 2012, 2, 19 ); var_dump( $date );
which shows:
object(DateTime)#1 (3) {
["date"]=>
string(19) "2012-02-19 16:37:58"
["timezone_type"]=>
int(2)
["timezone"]=>
string(3) "EST"
}
As a reminder of the three different types of timezones that can be attached to DateTime objects:
A UTC offset, such as in new DateTime( "2012-02-29 -0500" );
A timezone abbreviation, such as in new DateTime( "2012-02-29 EST" );
A timezone identifier, such as in new DateTime( "2012-02-29 America/Montreal" );
Please also be aware that only DateTime objects with "type 3" timezones attached to them will calculate correctly over Daylight Saving Time boundaries.
If you want to learn more about Dates and Times, and how to use them with PHP, please get a copy of my book "php|architect's Guide to Date and Time Programming".
Someone watching over my shoulder recently had never seen the ubiquitously-useful iterator_to_array() before. I'm sure they weren't alone and since I just typed it again, I thought I'd share a snippet.
Mostly I find this useful when I'm working with collections of data as these often present themselves as an object that you can foreach() over, but you can't dump it directly. If the object in question implements the Traversable interface, you can instead pass it into iterator_to_array to get the data as an array.
Consider for example my code which finds records in a MongoDB database; this returns a MongoCursor object, so when I var_dump() it, all I get is a little output telling me that's what sort of an object it is! Using iterator_to_array(), I can grab an array that I can quickly use to check what I got back:
$people = $db->people->find()->sort(array("created" => -1));
print_r(iterator_to_array($people));
In this case, I know there are only two rows in my database so it is a useful diagnostic tool as I put in the first pieces of a new application. Do be careful though about using this function on potentially large datasets! One of the best things about cursors is precisely that they avoid bringing in everything in one go, in case the data set is too large, so there are times when you won't want to put it all into an array at once. However for the times when you do - now you can :)
Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist. This post was originally published at LornaJane
Wow. Last week’s opinion piece about switching from Netbeans to Sublime Text 2 has been the most popular blog post I’ve written for quite a while.
As the interest seems to be there, I thought it would be a great idea to follow up with a post taking you step by step through how I’ve set up Sublime Text 2 for PHP development, and showing you some of the useful features that you get out of the box with Sublime Text 2.
You’ll find the details below, and as a bit of an experiment, I’ve also put the details together in a series of YouTube videos for those folks who’d prefer to see ST2 in action. The video directly below is the first in the playlist, and I’ve also put the video for each feature separately further down. If you like the videos, please do click the ‘Like’ button on YouTube so that I know :)
Tip: If you can’t see any YouTube videos on this page, you might need to switch off your browser’s AdBlock plugin and then reload the page.
Install Package Control, Soda, And A Syntax Highlighting SchemeOut of the box, Sublime Text 2 is a very good text editor. It’s so good, in fact, that I’ve seen people use it in its vanilla form perfectly happily for days and weeks before realising that it can be enhanced with third-party plugins!
The first plugin I recommend installing is Will Bond’s Package Control (installation instructions). Package Control is a plugin that automates the job of installing and upgrading plugins. After you’ve installed it, restart ST2, and then you’ll find a new “Package Control” menu option at the bottom of the “Preferences” menu.
There are over 200 community plugins currently available for ST2. You’ll find them by going into Package Control and selecting the ‘Discover Packages’ option. This takes you to the community packages webpage, where you can browse or search through the available packages. It’s worth going back and checking this page from time to time, as new packages are being added on a regular basis.
The next thing I normally do is reskin ST2. This is entirely a personal preference! Using Package Control, install the ‘Soda’ Theme plugin; this downloads the plugin, but does not activate it. Then, open up the ‘Settings – User’ preferences file (this is a JSON file), and add the following to tell ST2 to use the new theme:
"theme": "Soda Dark.sublime-theme",
You’ll notice a change straight away, but will probably need to restart ST2 for it to pick up all of the new theme properly.
Finally, I setup syntax highlighting to suit. ST2 ships with a number of these, and you can (if you wish) feed it any colour scheme originally created for TextMate. I prefer to use the ‘Phix Color Scheme’, which is available through Package Control.
Editing User PreferencesIn ST2, nearly all of the configuration is done by creating and editing config files. There are no user interfaces to click through, just JSON files to edit by hand. There are a few of these files, and the basic idea is that there’s nearly always a ‘default’ config file (which contains the defaults that ST2 or its plugins ship with), and ‘user’ override files.
If you go into the Preferences menu, you’ll see a ‘Settings – Default’ option. This opens the default settings file that ST2 ships with. It’s very well documented, and well worth a browse through to see if there’s anything in there that you’d like to tweak. Don’t make changes to this file; instead, open the ‘Settings – User’ option on the Preferences menu, and put your changes in there. That way, your preferences will be preserved between ST2 upgrades.
Finding Classes With The Goto Anything PaneThere are two ways you can open files in ST2. One way is to navigate through your list of folders in the Project pane on the left hand side of the screen, clicking around with the mouse and drilling down to find the file that you’re looking for. It works … but t
Truncated by Planet PHP, read more at the original (another 11757 bytes)
I’ve talked a lot on this blog about life and career in this blog recently, as to help developers become more productive members of a functioning business team. It’s a topic that is near and dear to me, and one that is essential for anyone looking to progress their career.
But if you want to really dig deep into this topic, then drop a mere $40 and check out the Day Camp 4 Developers conference. One day and you’ll hear some great talks such as these:
And one from your’s truely as well…
Loving what you are seeing? Curious on how to take your career from developer to manager? Then definitely sign up today at [dc4d4.eventbrite.com] .
Lately I have been very involved with code quality, not just in terms of testing and actually working, but also on a deeper level, readability and plain good architecture. At my previous employer we had been working for a good while already applying rules from “Object Calisthenics” a concept by Jeff Bay, a simple set of exercises that helped identify bad code and improvements points. Once I saw this book show up at O’Reilly I did not blink and made a purchase.
“The Art of Readable Code” was written by Dustin Bowell and Trevor Foucher and basically focuses on concepts and suggestions to make you code not just readable, but comprehendible by other developers, or as the author’s suggest, yourself in six months. Code readability is a topic that I truly believe the PHP community does not focus enough on and i really wanted a look at this book to see what kind of ideas it had and what I could do my best to bring to the attention of other developers.
The book does not focus on any one language and has examples from PHP, Python, Java, Javascript, C and C++, which is great. But the concepts are presented in a very verbose and conversational form so that the pieces of code really play a small part and it does not matter if you do or do not know any of these languages, any developer should be able to pick it up. The book goes from variable naming, to commenting, to refactoring and even into transforming ideas into code and testing, it really does a great job of describing various developer downfalls. I even picked up a few tips and added them to my talks about refactoring and writing better code, its will surely be on the recommendation page at the end.
After reading this book you will look at you code a little different, I can assure you. I agree with most of what’s on the book (except part of the test chapter) and i really believe more developers should see these points and work on them. So if you write code, pick up this book, its a very light read and very pleasant one as well. It kept me good company on the trams to and from work, and even walking, that’s how easy going it is. So go get it, read it, learn from it and make your code better.
The Art of Readable Code
Simple and Practical Techniques for Writing Better Code
By Dustin Boswell, Trevor Foucher
Publisher: O’Reilly Media
Released: November 2011
Pages: 204
Print ISBN:978-0-596-80229-5 | ISBN 10:0-596-80229-3
Ebook ISBN:978-1-4493-1417-0 | ISBN 10:1-4493-1417-1
Buy it on Amazon
© Rafael Dohms for Rafael Dohms, 2012. |
Permalink |
No comments
Want more on these topics ? Browse the archive of posts filed under Books, Pessoal/Off-topic, PHP, Reviews.
With all PHP topics, nothing counts more than their practical application. This is why thePHP.cc offers highly interactive and practical workshops. Based on their own specific needs and questions, the attendees decide on the topics that are covered. They experience the development of new code at first hand, following their own agendas rather than those of the three trainers.
The first PHP Summit with workshops presented in English will be in London in May. And these are the workshops:
Update PHP: Leverage New Features and Technologies Workshop with Sebastian BergmannPHP 5.3 and PHP 5.4 help developers in their daily routine with a plethora of relevant improvements. Get to know the innovative features of these new versions and learn how to apply them in practice. Discover the potential of emerging technologies such as memcached or ZeroMQ and learn how they can solve your problems.
Unclean PHP: Identify, Refactor, Avoid Workshop with Sebastian BergmannSooner or later unclean code becomes a damn nuisance. And not only for the developer who has to maintain it. Changes and extensions make the code more and more uneconomic. Learn how to detect unclean code using static analysis and how to refactor it with testability and maintainability in mind. Learn how to avoid unclean code by applying the SOLID principles and writing sustainable code.
Best Practices: From the Real World for the Real World Workshop with Arne BlankertsOf course you can reinvent the wheel every day. You just do not have the time to do so, plus it is no fun, and bugs can creep into the same places over and over again. Clever solutions exist for many bread-and-butter problems that only deviate slightly from already solved ones. This workshop shows the programming concepts to achieve this in a live coding session that is entirely driven by the audience's requests and invites to a discussion of tools and techniques.
Safely Prepared for Errors Workshop with Arne BlankertsPrograms and websites have errors. Always. They become apparent when users enter wrong, invalid, or unexpected input, when access to the database is suddenly not possible, or when the disk is full. Various approaches to safely handle these and other problems are presented and discussed in this workshop. How to correctly use exceptions, why a custom error handler can be helpful, and what debugging has to do with security these questions and more will be answered intuitively and vividly.
Object-Oriented Progamming (OOP) in PHP I: Fundamentals Workshop with Stefan PriebschThis workshop answers the question what object-oriented programming is all about. It gives an introduction to OOP with PHP that goes beyond the known standard examples. In addition to presenting the fundamental principals of OOP it also highlights interesting features of the Standard PHP Library (SPL) and how they can be applied in practice. In addition to imparting factual knowledge the workshop presents a mindset that allows you to avoid overly complicated approaches.
Object-Oriented Progamming (OOP) in PHP II: Advanced Topics Workshop with Stefan PriebschThis workshop introduces attendees that are already familiar with the foundations of OOP to advanced topics such as Dependency Injection, abstract classes, and interfaces as well as best practices for successful object-oriented programming. A live coding session makes the presented techniques tangible. In addition to imparting factual knowledge the workshop shows that good solutions are simple solutions: simple objects are easier to reuse and test and thus help to avoid mistakes.
Testing PHP Application: Fundamentals Workshop with Sebastian BergmannThis workshop imparts the fundamental information and skills for the writing of Unit Tests, Database Integration Tests, Edge-to-Edge Tests, and End-to-End Tests with PHPUnit. You will learn everything you need to know to write, organize, and run tests with PHPUnit.
Testing PHP Applications: Advanced Topics Workshop with Sebastian BergmannCraftily leverage PHPUnit: Attendees of this workshop will learn PHPUnit best practices and field-tested strategies for the introduction of testing measures into legacy projects. A range of examples will help the attendees to develop a sense for hard-to-test code and bad tests. They will learn how to refactor legacy code for testability and how to avoid common pitfalls when writing unit tests.
Insider's Tip XML: Applications the Smart Way Workshop with Arne BlaTruncated by Planet PHP, read more at the original (another 6218 bytes)
This is something experimental I have been working on for our chef deployments. So the objective was/is to find a sane way to install PEAR packages and install dependencies with composer.
execute in chef recipesIn chef recipes, almost everything is a resource. In case you're just getting started with Chef, a list of current resources is available on the Opscode Wiki. It's a link I put in my browser bar since I frequently work on chef recipes.
Some examples for resources are:
The above list are examples — so there is more. But if there isn't a designated resource, you can always use an execute block.
An example for an execute block is the following:
execute "discover a pear channel" do command "pear channel-discover easybib.github.com/pear" end
This works pretty well, but it is also not very robust.
Fail hardBy default whenever a command fails, chef fails hard.
To illustrate what I'm talking about, let's test and execute the command from our execute block multiple times on the shell to see its exit status ($?):
till:~/ $ pear channel-discover easybib.github.com/pear Adding Channel "easybib.github.com/pear" succeeded Discovery of channel "easybib.github.com/pear" succeeded till:~/ $ echo $? 0 till:~/ $ pear channel-discover easybib.github.com/pear Channel "easybib.github.com/pear" is already initialized till:~/ $ echo $? 1
So whenever a command returns not 0, chef will bail.
One solution is to brute-force your way through these things with ignore_failure true in your execute block. But that's usually not a great idea either because it hides other issues from you (and me) when we need to debug this later on.
For example, if this PEAR channel is unavailable during your next chef-run, it would be much, much harder to find the root cause as of why the install commands failed.
Another solution is using the not_if or only_if options with execute:
execute "discover a pear channel" do
command "pear channel-discover easybib.github.com/pear"
not_if do
`pear channel-info easybib.github.com/pear`
end
end
If the command wrapped in not_if succeeds (success is exit status), we would skip the execute block.
Since I discovered not_if and only_if, it allows me write recipes which work in most cases. More robust code, which allows me to re-execute recipes on already running instances. So for example when I update a recipe or configuration file which is distributed through a recipe I can re-run the entire recipe and it will not fail but instead complete successfully.
One problem remains with this approach I end up doing the same checks again and again.
... more after the jump.
At the PHP UK Conference Rasmus mentioned that he wants more people contributing to PHP. There are plenty of ways how you can do that.
The first one is testing release candidates RCs of PHP releases. You can do a very basic test by running "make test" after compiling PHP, but it's even a lot more important to test your own code with the RCs. This often catches more things as the PHP Development Team doesn't quite know how everybody uses PHP. It's a little bit late in the game now for PHP 5.4, but head over to [qa.php.net] for a quick intro and a link to where to download the RC8. PHP 5.4.0 is not released yet, so testing the RC is still very valuable. Hurry up though, as this is most likely the last RC for 5.4.0! Also, you are not allowed to complain about PHP 5.4 breaking stuff unless you've tested RCs :-)
The second thing that Rasmus brought up is a new feature on [bugs.php.net] It's modelled like the "random cute cat picture" features that sites like [cuteoverload.com] use for giving you a random cat picture. Except that we don't show cute cats, but a random PHP bug. If you have a few spare minutes go hit [bugs.php.net] until there is either an unconfirmed bug report that needs triage, or perhaps you can just fix it because you're a C wizzard. This is hopefully a better time waster than random cute cats.
Oh, yeah, go test the PHP 5.4.0 RC!
Note: This article was originally published on the march/2011 issue of php-architect. If you like it keep a close eye on the Community Column in the magazine, where i get the chance to write alongside other awesome community people.
"Our function as community leaders is to enable people to be the best they can in the community that they have chosen to be part of." -- Jono Bacon
This quote comes from Jono Bacon's book: "The Art of Community", and I like it because it puts somethings in perspective. Communities are a interesting manifestation of human social skills, a truly incredible joining of people by a single motivation, in our case the motivation is PHP, be it helping, learning, self-promotion, work or any more of a wide gamma of roads that lead to getting in touch with this great force. Community leaders are even more intriguing species, people who try to lead and organize this controlled chaos, and they don't even get paid for it.

PHPSPUG during our TestFest lunch
But as Jono puts it, the Community leader is really not a leader, someone on top of the stage with all the flood lights on him. The leader is a catalyst, that spark that can lead to a forest fire, ok not the best reference, but you get the point. Leaders are there to inspire people, give them the initial push and then literally get out of their way and let them go where their inspiration and self-drive takes them, as Jono says, an "enabler".
Its very interesting to observe Communities, their manifestations and their growth. They seem to have life of their own, to grow, mature and expand as a group in this kind of biological process, leaders are always present, but they are a cyclic occurrence, old ones move on, new ones take over and yet the community keeps going. I have been observing communities for a long while, here in Brazil and a few overseas also, thanks to opportunities from all the major conferences that help all of us "community geeks" get together and start brainstorming, sort of like this column.
Our community seems to have started somewhere in 2006, the first User Group showed up with what was, back then, this crazy idea to hold a national PHP Conference. They started small with a few local events in São Paulo. By the time the conference came around there was this great sense of awareness that we were not alone. I quickly made the wise choice to gather a few savings and get myself a ticket over. It was truly an incredible experience for me, my first PHP Conference, this incredible feeling of being in a place with so many other people speaking the same language, same topics and understanding when I started talking about frameworks, mvc patterns and how to deal with heavy traffic. See, back then I was a one-man team and had barely started using mailing lists, that conference was an eye opener, it showed me that I was naught but a mere beginner in this great career of a PHP Developer. It showed me there was this incredible source out there, one you could tap into and get this amazing collection of knowledge. I stood there watching all of those speakers talk about these incredible things, sharing all of this information, an overdrive of ideas and inspiration.
By the end of the conference I had one clear though: "I need to learn, and I want to share, next year I want to be a speaker". That moment changed my life professionally and that conscious decision to be part of this "community" has been paid back in much more then triple. As history goes that year along with two great friends (Adler Medrado and Pablo Sanchez) we founded our first User Group, PHPDF on Brazil's capital. And we were not alone, that single conference put so many ideas in so many heads that User Groups started popping up all over the country. The PHP community in Brazil started taking shape, we started to see that we were not quite the "few and scattered" group we believed, we were huge and ready to move to new heights.
Fast forward to 2010. Brazil has over 21 User Groups, almost one in every single state, from the amazon to the atlantic forest and going through all our huge metropoles. That national conference is now just the crowning conference at the end of the year, numerous other smaller conference are held during the year, producing new ideas and more and more groups every year, not to mention launching new speakers and bri
Truncated by Planet PHP, read more at the original (another 4024 bytes)
I'm implementing OpenID for SemanticScuttle, your self-hosted social bookmark manager. To log in with OpenID, you need to know your OpenID URL, which many people do not know, and don't want to know. Most know their email address, and thanks to WebFinger, this is all you have to know!
WebFinger enables applications to discover information about people by just their e-mail address - for example their OpenID URL!
I didn't find a single standalone WebFinger library for PHP, so I asked on StackOverflow, but did not get any responses. Failed to stand on the shoulders of giants, I went the hard way and implemented it all myself: Net_WebFinger, based on XML_XRD.
ImplementationWebFinger weaves RFC 6415: Web Host Metadata with LRDD which both use XRD files.
Thus the first step was to build a clean XRD library for PHP, with an intuitive API and 100% unit test coverage. I proposed the XML_XRD package on 2012-02-01, called for votes 8 days later. It was accepted with 11 votes. Extensive documentation does also exist now.
After the foundation was laid, I proposed the Net_WebFinger package. It was accepted as new PEAR this night, and just some minutes ago it got its first official release and a lot of documenation.
UsageSo, discovery is easy now! First, install the PEAR package:
$ pear install net_webfinger-alpha
Now the PHP code:
<?php require_once 'Net/WebFinger.php';
$wf = new Net_WebFinger();
$react = $wf-?>finger('user@example.org');
if ($react->openid !== null) {
echo 'OpenID provider found: ' . $react->openid . "\n";
}
//list all other links:
foreach ($react as $link) {
echo 'Link: ' . $link->rel . ' to ' . $link->href . "\n";
}
?>
WebFinger CLI
Net_WebFinger ships with a command line client that you can use to try it out. Find it with
$ pear list-files net_webfinger|grep cli doc /usr/share/php/docs/Net_WebFinger/examples/webfinger-cli.php
Yahoo and Google already support WebFinger. Distributed social networks like status.net (that powers identi.ca) and Diaspora use WebFinger to distribute public encryption keys, OStatus and Salmon URLs. You can try one of those user addresses, too.
$ php /usr/share/php/docs/Net_WebFinger/examples/webfinger-cli.php klimpong@gmail.com Discovering klimpong@gmail.com Information secure? false OpenID provider: [www.google.com] Link: [portablecontacts.net] http://www-opensocial.googleusercontent.com/api/people/ Link: [portablecontacts.net] http://www-opensocial.googleusercontent.com/api/people/102024993121974049099/ Link: [webfinger.net] http://www.google.com/profiles/klimpong Link: [microformats.org] http://www.google.com/profiles/klimpong Link: [gmpg.org] http://www.google.com/profiles/klimpong Link: [specs.openid.net] http://www.google.com/profiles/klimpong Link: describedby: [www.google.com] Link: describedby: [www.google.com] Link: [schemas.google.com] https://www.googleapis.com/buzz/v1/activities/102024993121974049099/@public
$ php /usr/share/php/docs/Net_WebFinger/examples/webfinger-cli.php singpolyma@identi.ca Discovering singpolyma@
Truncated by Planet PHP, read more at the original (another 1043 bytes)
It’s been a few weeks since I was in Belgium for the excellent 2012 PHPBenelux Conference, which brought together beer, chocolates ( at least for the wife ) and PHP together for an excellent two days of fun and community. And I did a new talk, Working successfully outside the cube, which was a new talk for me that I got great feedback from.
But, from reading the comments, there’s two points I didn’t really hit on well during the talk, so I figured I take the time now and try to answer them here.
What is the cost to my employer to be remote?
There isn’t a hard and fast answer to this question, and it depends upon your organization’s structure and policies along with what technologies they already have in place. Generally speaking, you’ll need this:
It’s probably best to investigate this first with your boss to see if there are any hurdles you need to get past, but chances are good the infrastructure is already in place.
What are some best practices for collaboration tools for remote workers?
While everyone’s organization is different, here’s what I find that works best for me:
As for soft skills in effective communication, check out a blog post I did about respecting other’s time a while back for some good points on effectively planning meetings and learning how to make sure your interactions are productive with others. And next weekend I’ll be doing a talk at the virtual Day Camp 4 Developers conference around how to navigate the business world, which should also help you out in your quest to better plug into your organization and be productive while a remote worker.
Hope this answers everyone’s lingering questions from the talk. Thanks again for all the great feedback, I hope to do it again soon…
Well, I’ve been a little lazy around here and haven’t posted since the beginning of the year. I figured I’d fix that by posting an update about a few things going on around here.
First off, since the schedule was just released, I’ll mention that I’ll be presenting at this year’s Dutch PHP Conference with three different sessions (well, kind of just two):
No, I didn’t repeat myself – the first session and the last session are on the same topics – they’re just different lengths. The tutorial on the first day will get more into coding and examples of ExtJS+ZF and the second shorter session will just give a high level overview of each tool and how they hook together. If you’re interested in the “guts” of an Ext-based app, you’d do better in the Tutorial.
Also, for those that don’t know me, I’m a co-organizer of the Dallas PHP User Group. Last year we decided to put on a local PHP-centric event and it was a great success. So, we’re back this year with the Lone Star PHP Conference 2012. We’ve just wrapped up our Call for Papers and are in the process of selecting the best fits for our schedule.
We’ll be announcing the schedule and opening the registration soon, so keep an eye out on the Lone Star PHP conference site for more updates!
This weekend we have been busy hacking on Composer in our office together with Nils Adermann and Volker Dusch. We wanted to push the project forward a bit faster than the odd free evenings usually allow, and I would now like to introduce the changes we made.
Development versions handlingThe former master-dev and similar *-dev versions we used to have were causing quite a few issues, so we decided to overhaul that behavior in a way that allowed us to get more consistency and fix a few long standing issues. For example dev versions can now be locked to exact commit revisions, and they will update to the latest revision when you do an update, no need to delete them from disk beforehand.
Basically dev releases are now simply branch names with a dev suffix – for numeric branches which are comparable – or a dev prefix for textual names that are not comparable, like feature branches and master. There is no way to specify the version manually anymore in your repository’s composer.json, since that was causing potentially dangerous issues with feature branches conflicting with the original ones.
If your package depended on a master-dev version, you should now depend on dev-master. If your package depended on something like the Symfony2 2.1.0-dev version, this one also is now dev-master since it is in the master branch. Older feature branches like 2.0-dev which is the 2.0 branch and not master are unaffected by this change.
This change will break many packages out there that rely on -dev packages of any kind, and we hope everyone will update their composer.json files as swiftly as possible to make the transition less painful.
The Packagist version database had to be reset for this change, so things will look at bit empty for a couple of hours while everything is re-crawled. None of the packages are lost and you should not have to do anything except having a bit of patience.
Dependency solver stabilityNils and Volker have been doing big progress on bugfixing and testing the solver. Those are mostly highly technical details that I will not dive into here. But long story short many old bugs should be fixed, and then some. It may obviously have introduced regressions, so if you encounter any issues please report them with your composer.json file so we can easily reproduce.
DocumentationIgor has spent quite a bit of time on documentation, which you can see on github for now, and which should be migrated to getcomposer.org soon.
Packagist / GitHub integrationAnother great new feature coming from a pull request by Beau Simensen is the ability to let GitHub tell Packagist when you push new code to your repository. This should make package updates almost instant. It should be integrated into the GitHub Service Hooks soon enough, so if you don’t want to set it up by hand you can wait a bit, otherwise you can grab your API hook URL on your Packagist profile page, and add it in your repository.
Repositories configurationIt seemed that the way custom repositories are configured was confusing, so we took the chance to make it a bit clearer. Basically names are dropped and it’s all stored in a flatter structure that’s easier to remember. Documentation has been updated on Packagist.
All in all it has been quite a productive week-end and we will continue working on a few things today.
I’ve recently switched from using Netbeans as my PHP dev tool of choice to Sublime Text 2. Features-wise, I think Netbeans is great. During the years I used it, I never felt that there was a feature I needed that was missing at the time. But, like all the current crop of Java-based desktop IDEs, it’s so damn ugly [1] and slow [2] that I’ve had enough. I program because it’s something that I love doing, and anything that gets in the way of that … I’ve no time for any more. So when a work colleague introduced me to Sublime Text 2, I was in the mood to give it a go, and 3 months on, I haven’t opened Netbeans once.
I’ll be the first to say that Sublime Text 2 isn’t for everyone.
Given all of that, why have I switched?
Truncated by Planet PHP, read more at the original (another 7008 bytes)
In 2007, the first Plat_Forms contest took place with support of Zend Technologies, University of Berlin, Heise Publishing Company and OSBF. It was a web development platform comparison like it had never been done before: 9 teams in controlled environment doing the same task in a limited time. During that time, the team of Prof. Lutz Prechelt collected data and after the contest, the results together with the data regarding the workflow of the individual teams was evaluated in a scientific way.
Back then, the PHP teams had outperformed Java and Perl in terms of development productivity and usability of the resulting applications. The results of this contests helped to position PHP in many large organisations because they proved common prejudices against PHP wrong: No, PHP is not insecure, no it is not slow, etc.
In 2011 a second contest was helt with 16 teams. Unfortunately the results were not that inspiring this time (as shown here some time ago). Now the third event of this kind is coming up:
Plat_Forms 2012 will take place on April 3rd and 4th, 2012 in Berlin, Germany.
Plat_Forms 2012 will focus on scalability and cloud computing. Unlike in 2007 and 2011, this year's teams will implement a highly scalable web service on Amazon Web Service infrastructure.
Again, multiple teams consisting of 3 persons each are invited for each web programming platform: PHP, Ruby, Perl, Java. They are searching for strong PHP teams with the will to compete.
PHP needs you! More information here.

A while ago ago, I quit Flickr to work on a “social geo mobile local” startup that was secret to everyone except some closest friends and family. Today, we are finally able to talk about it in public!
The great team at 2bkco is happy to announce Pinwheel (for now in private beta). Our fearless leader Caterina Fake has posted an introduction to what I think will be an awesome service for years to come.
If you’d like to leave some notes around the world for people to find, come on over to Pinwheel and sign up!
Since becoming freelance 18 months ago, I've taught a number of courses at my excellent local tech training centre, NTI Leeds. Over the next few months we're running some one-day PHP courses (see my course dates page for more detail and the dates, all these are in Leeds although I'd like to run them elsewhere too), targeted at a particular area or set of skills. These are areas that I find myself delivering consultancy or training on frequently, or things I teach when I go places and realise these gaps exist in their knowledge. Does this match your experiences of "things I wish PHP developers knew - including me"?
I like design patterns and the joy of teaching this is that it helps to stop some of the big words and unfamiliar terms in object-oriented programming from seeming like rocket science. Most people will quickly tell me "oh, I've been using this all along!" - which is exactly the point :) Teaching a few design patterns also gives a great vehicle for teaching some of the advanced OOP concepts in a more interesting way than "this is an interface".
Databases and PDOWeb developers don't know what they don't know about databases! Being able to join multiple tables with different types of join and aggregate data correctly allows you to learn how to normalise data and not be afraid to implement the schema changes. I like to teach how to do this and get everyone confident with it all. The PDO extension is a fabulous way of working with databases and I think the prepared statements are in everyone's interests, so that forms a good part of the course too.
PHP ToolsA course for all the allied skills you need - configuring apache, a bit of linux command line, quality and performance tools (xhprof, php code sniffer, api documentation, and more) are all included. There's a splash of source control (because it is the basis of all things!) and we also talk about strategies for deployment (with phing as an example) and managing things like configuration management and database schema changes. In a one-day course there isn't time to teach unit testing or continuous integration properly but they do get a mention and I try to point interested parties in the right direction for more information.
PHP CoursesIf any of the above sound interesting and you want to come and learn this stuff with me for a day, you can book the courses through NTI. Feel free to ping me with questions, comments, or tell me why this isn't the right topic for you - always interested to hear others' viewpoints.
Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist. This post was originally published at LornaJane
Since becoming freelance 18 months ago, I've taught a number of courses at my excellent local tech training centre, NTI Leeds. Over the next few months we're running some one-day PHP courses (see my course dates page for more detail and the dates, all these are in Leeds although I'd like to run them elsewhere too), targeted at a particular area or set of skills. These are areas that I find myself delivering consultancy or training on frequently, or things I teach when I go places and realise these gaps exist in their knowledge. Does this match your experiences of "things I wish PHP developers knew - including me"?
I like design patterns and the joy of teaching this is that it helps to stop some of the big words and unfamiliar terms in object-oriented programming from seeming like rocket science. Most people will quickly tell me "oh, I've been using this all along!" - which is exactly the point :) Teaching a few design patterns also gives a great vehicle for teaching some of the advanced OOP concepts in a more interesting way than "this is an interface".
Databases and PDOWeb developers don't know what they don't know about databases! Being able to join multiple tables with different types of join and aggregate data correctly allows you to learn how to normalise data and not be afraid to implement the schema changes. I like to teach how to do this and get everyone confident with it all. The PDO extension is a fabulous way of working with databases and I think the prepared statements are in everyone's interests, so that forms a good part of the course too.
PHP ToolsA course for all the allied skills you need - configuring apache, a bit of linux command line, quality and performance tools (xhprof, php code sniffer, api documentation, and more) are all included. There's a splash of source control (because it is the basis of all things!) and we also talk about strategies for deployment (with phing as an example) and managing things like configuration management and database schema changes. In a one-day course there isn't time to teach unit testing or continuous integration properly but they do get a mention and I try to point interested parties in the right direction for more information.
PHP CoursesIf any of the above sound interesting and you want to come and learn this stuff with me for a day, you can book the courses through NTI. Feel free to ping me with questions, comments, or tell me why this isn't the right topic for you - always interested to hear others' viewpoints.
Lorna is an independent web development consultant, writer and trainer, open source project lead and community evangelist. This post was originally published at LornaJane
If you're going to be in or around Boston tomorrow (Wednesday) night, I hope you'll join me at the Microsoft NERD Center, where I'll be giving my first talk in more than a year and a half.
I'm going to be speaking about the science of human behavior and why perception matters, even if all you care about is something like security. This talk is a lot of fun, because I mostly just talk about stuff that I find really interesting. There are more videos than bullets, and more science than code.
After the talk, I have it on good authority that we'll be enjoying stimulating conversation and drinking good beer.
I use WordPress for this web site. To pretty up source code examples in my posts, I use the excellent SyntaxHighlighter Evolved WordPress plugin. The WordPress theme I use, Fluid Blue, does something with its CSS such that it and SyntaxHighlighter appear to conflict. The result is that source code examples processed by the plugin are displayed with a font size that’s too small to read comfortably.
In doing some digging, I learned about the child themes feature of WordPress, which allows you to effectively extend an existing theme. I created a directory under wp-content/themes called fluid-blue-custom. In this directory, I created a styles.css file with these contents:
/*
Theme Name: Fluid Blue (Custom)
Template: fluid-blue
*/
@import url("../fluid-blue/style.css");
body .syntaxhighlighter code, body .syntaxhighlighter .gutter { font-size: 12px !important; }
The Template line of the comment block indicates that this theme is a child theme of the existing Fluid Blue theme that resides in the wp-content/themes/fluid-blue directory. The @import line pulls in the styles.css file from that directory, after which I can apply any CSS overrides I like. The last line is a CSS rule specific enough to override applicable rules from the parent theme in order to increase the font size to something more easily readable.
It appears I’m not the only one who’s encountered this issue, so I hope this post helps someone else.
I’m currently working on a project that involves running Drupal on Amazon EC2. To save time in setting up future new VM instances, I decided to take the opportunity to learn puppet. For the time being, I’m using a single VM to run the full LAMP stack and running puppet without a server by copying my puppet manifest to the VM and using puppet’s apply command to apply it locally. However, this manifest can easily be adapted for a multi-VM environment. After some tinkering, I came up with the code below.
class web {
package { 'httpd':
ensure => 'present',
}
package { 'php':
ensure => 'present',
}
# Update this to use your respective time zone value
exec { 'php_config':
command => '/bin/sed -i "s/^;date.timezone =/date.timezone = \'America\/Chicago\'/g" /etc/php.ini',
require => Package['php'],
}
service { 'httpd':
ensure => 'running',
enable => true,
hasrestart => true,
hasstatus => true,
subscribe => Package['httpd', 'php'],
}
# Drupal requirements
package { ['php-pdo', 'php-mysql', 'php-xml', 'php-gd', 'php-mbstring']:
ensure => 'present',
require => Package['php'],
}
}
class mysql {
package { 'mysql-server':
ensure => 'present',
}
service { 'mysqld':
ensure => 'running',
enable => true,
hasrestart => true,
hasstatus => true,
subscribe => Package['mysql-server'],
}
# Equivalent to /usr/bin/mysql_secure_installation without providing or setting a password
exec { 'mysql_secure_installation':
command => '/usr/bin/mysql -uroot -e "DELETE FROM mysql.user WHERE User=\'\'; DELETE FROM mysql.user WHERE User=\'root\' AND Host NOT IN (\'localhost\', \'127.0.0.1\', \'::1\'); DROP DATABASE IF EXISTS test; FLUSH PRIVILEGES;" mysql',
require => Service['mysqld'],
}
}
class {'web': }
class {'mysql': }
With this code saved to a file called manifest.pp (.pp being the file extension for puppet manifests), I can spin up a VM and do the following to set it up:
scp -i key.pem manifest.pp ec2-user@host:~/ ssh -i key.pem ec2-user@host sudo yum upgrade -y sudo yum install -y puppet sudo puppet apply manifest.pp rm -f manifest.pp exit
At this point, I have a basic Apache/MySQL/PHP configuration capable of receiving a Drupal 7 installation.
s you probably know, we at IKS have been working to decoupled content management through semantic technologies. CreateJS, together with the VIE library provide the user-facing part of this approach.
Traditional content management has been very monolithic, meaning that by choosing a particular editing interface, CMS users also have to take the web framework, programming language and content storage mechanism mandated by the developers of their system. By splitting the CMS to the separate concepts of user interface, web framework, and content repository we can provide implementers a greater degree of freedom, and allow CMS developers to focus on the functionality where they can best make a difference.
What is Create?With CreateJS, content management system developers can provide a simple, fast, and modern editing interface to their end-users. The UI is completely built in JavaScript, and can be integrated with three easy steps:
Create provides functionality like in-page content editing, managing of content collections (like article lists), running workflows for content, and handling images and content tagging. The jQuery UI plugin -based structure allows CMS developers also to implement their own additional functionality. This also makes it possible to either use the whole Create UI as-is, or just to take the parts of it that fit the UX concept of a system.
The Create UI was initially made for Midgard CMS, but has since been generalized so that it works anywhere. This approach has already gained some popularity, with CreateJS widgets being used in projects like Symfony CMF, Drupal, and OpenCMS.
The January hackathonTo push CreateJS forward we organized a hackathon in Zurich, Switzerland in the early January. Participants came from different IKS project partners and CreateJS early adopters.
Some of the results were:
Image insertion, link management, and content tagging have been designed to work together so that they can find about annotated entities thanks to the Apache Stanbol engine and provide intelligent suggestions on related content.
Moving forwardThe important next step is to consolidate all these changes into the CreateJS codebase and to ensure that everything works smoothly together. Our continuous integration setup would also benefit from a larger number of tests.
After that we can consider new features, including things currently under discussion.
Helping CMSs to integrate this common user interface (or parts of it) is also a major task for this year. If you're interested in using CreateJS for your system, be sure to let us know! And also follow the progress on GitHub.
PHPStorm's File template settings are very versatile. They allow you to not only make a file template, but also allow you to parse out redundant elements (such as licensing) in the template by allowing an includes section. In your File Template, any undefined variable automatically elicits a prompt from PHPStorm.
PHPStorm allows you access to the includes section via the #parse directive. If you're want To have Custom variables to be filled in correctly via prompt, you will need to have the variable declared in the template.
Example
"chance license.php"
/**
* @package ${Package}
* @author Chance Garcia
* @copyright (C)Copyright ${YEAR} chancegarcia.com
*/
In the above includes example, I'm wanting to have a custom variable named Package. I can only cause PHPStorm to prompt for this value if I include the variable in my template. If I'm already using the variable in the template, then it will fill in when the includes file is parsed.
Example:
<?php
#parse("chance license.php")
class ${Package}_#if(${ExtraClassInfo} != "")${ExtraClassInfo}_#end${NAME}
{
}
In the above template, the ${Package} variable will be given a prompt since it is used in the template and an unknown variable and the parsed "chance license.php" include will be able to use that prompt value.
I am also using another variable to Prompt for extra class name information. Since PHPStorm uses Velocity Template Language (VTL), I am able to use the VTL conditional syntax to insert that information if it is entered and ignore it if it is not. This technique is useful in a situation where you want your include file to have a custom variable value but do not need to display this value in your template.
Example:
<?xml version="1.0"?>
<!--
#if(${Package})#end
#parse("chance license.php")
-->
In the above example, we make PHPStorm prompt for the custom value needed for out parsed include file. This gives us our expected include file without printing our custom variable anywhere else in our template.
Over the last few days I’ve finally fixed a data enumeration bug that was haunting a new feature in Shazzer. Originally Shazzer just mutated one character at a time to discover characters which influenced the fuzz vectors in interesting ways. I decided to expand that to include data. I called the feature “datasets” because you could assign a placeholder to a set of data. Using this placeholder it then becomes easy for you to generate a vector that checks each value in the dataset and not only that but how that data relates to another dataset.
So what does that actually mean when it comes to vector creation? Here is an example enumeration vector:
<*datahtmlelements* *datahtmlattributes*="javascript:parent.customLog('*datahtmlelements* *datahtmlattributes*')"></*datahtmlelements*>
*datahtmlelements* refers to a dataset and in this instance we are talking about html elements, so the placeholder will be replaced by “iframe”, “b”, “html” and so on, the same this will happen to *datahtmlattributes* but this time using each attribute. Shazzer checks your vector for how many instances of placeholders you have and then automatically creates a loop within all the data so it enumerates each dataset within a nested loop of up to 5 separate datasets. The amount of data is split between a maximum of 10,000 iterations so your data will all be enumerated no matter how big the total iterations are it will just take a long time for a lot of nested datasets
You can see in the vector that the placeholders are used more than once this enables you to log any interesting results, so here we use the customLog function in Shazzer to send the html element and attribute that executes. Other logging functions are available and are listed in the preparation code when you create a vector.
Steps to create an enumeration vector1. Check datasets for which data you would like to enumerate. You can create your own dataset if the one you require doesn’t exist.
2. Click create and select “Data enumeration” from the vector type drop down.
3. Give it a nice descriptive name and some keywords to find the vector.
4. You don’t actually need to modify the preparation code unless you need to log something that doesn’t execute like CSS values for instance.
5. Construct your vector by clicking and data placeholders at the bottom and craft you code as if you’re in a loop of all the data structures you use.
6. Once your vector is complete you can now fuzz the vector by choosing it from the “Fuzz vectors” list. Once you’ve found your vector you can select a doctype then click “Fuzz all” to begin fuzzing.
In future you will be able to share these enumeration vectors between your twitter followers in order to distribute the workload between friends to help scan large datasets. Happy fuzzing!
One of my goals this year is to acquire new skills, so I've decided to start by learning JavaScript. As was the case when I learned html and CSS, it's a tricky endeavor, because I'm not exactly a beginner, and most stuff is geared toward beginners, which can make learning so inefficient that I lose my motivation.
I've decided to treat this effort just like I treat exercise, which is to focus on rhythm and consistency above all else. Don't break the chain. My days are packed, but I'm setting aside at least half an hour each day to do something related to learning JavaScript. As long as I hold myself to that and continue making progress, I'll be happy.
Why am I telling you this? One reason is to put myself on the hook, and another reason is so that I can share what I'm doing to learn JavaScript, in case you want to join me. (This also means those of you who have already been down this path can offer your sage advice.)
Since I've just started, I'm currently only using two sources:
Eloquent JavaScript This not only seems like a good introduction, but it also offers interactive exercises, which I think is going to make a big difference. Codecademy As you can see, I've already gone through some of the courses on Codecademy. The quality seems to be hit or miss, but I like the concept and the platform, and it allows me to dedicate very little time and still feel like I've made some progress.I also have a copy of JavaScript: The Good Parts that O'Reilly sent me back when they wanted Sean and I to write a similar book for PHP. I'm not sure if it's best used as a guide or a reference, though.
If you're a developer and don't already consider yourself a JavaScript expert, won't you join me?
My previous post, The MicroPHP Manifesto, resulted in much excitement. In between fits of rage and crying, I found some time to answer folks questions, and also discuss the topic on the /dev/hell podcast with my cohost Chris Hartjes. To summarize and address some of the common questions, I felt I should write a small FAQ.
Got a question? Ask me. I’ll add additional entries here as things come up.
So you think full-stack frameworks suck?No. I think sometimes they’re very appropriate. It depends on your needs: will the pros you get with library/component/framework X outweigh the negatives? If so, it’s probably a good choice. If not, it’s probably not.
You need a large framework to enforce best practices!Sometimes you do. My experience at FictiveKin has been that our small team is able to work faster, smarter, and more efficiently by minimizing the size of our PHP codebase and removing all unnecessary layers of abstraction. In some cases that meant not doing certain tasks in PHP anymore (almost all html generation was moved to the browser). In others, it meant ripping out a bunch of code and replacing it with a simpler solution that required far less boilerplate and replication. We still kept some code that had more dependencies than we’d like because the wins we get with it outweigh the downsides.
I’ve certainly seen situations where choosing a popular full-stack framework is a better idea. As teams get larger, enforcement of coding standards and not doing Dumb Shit becomes harder. Hiring and training engineers is usually easier with popular, full-stack frameworks. On the other hand, we’ve found that devs coming from non-PHP backgrounds liked how quickly they can be productive with simpler libraries and frameworks. Your mileage may vary.
So you’re saying we should write our own framework/libraries/components?Good God no. There is lots of very good, well-written code out there that’s already solved the problem you’re facing. Most of the time I don’t want to try to solve an issue like oAuth request signing, because it makes my brain hurt and I’d rather focus on building stuff. So, I’ll look for an existing solution that fits my needs first. I sometimes choose to write something from scratch because the existing solutions (that I can find – discovery is a whole other issue) don’t fit well with my existing application structure, or I feel it will introduce more maintenance issues than I’m comfortable with.
You should check out my microframework!Sure. Generally I think people should work on writing libraries/components, personally. We have plenty of framework choices. But this is PHP, so you have to write your own framework sometime.
Is “X” a microframework?Long answer: I tend to believe that the reference implementation of “microframework” is Sinatra. Routing, request/response objects, sessions, maybe some hooks for template rendering. Generally I think the inclusion of an ORM is a clear sign of non-micro-ness.
Short answer: I don’t care, really – and you shouldn’t either. If it works for you, awesome.
How do you choose what gets listed in the MicroPHP code collection?Generally I think about these things:
None of these are hard and fast rules, though. I encourage people to share things with me they think others would find useful.
Why do you hate Rush?I don’t. I like some of their songs, but don’t own any of their work. I also think they’re incredibly smart, talented musicians. My point was to suggest there are other valid approaches, not to reject complexity outright.
A quick update about CSP. Browsers are well on their way to all adopt the specification.
An early draft was already adopted by Firefox 4, and I just found out that it's also working in Chrome, Safari and IE 10.
IE10 and FF are using the following header:
- X-Content-Security-Policy: default-src 'self'
While Safari and Chrome use:
- X-Webkit-CSP: default-src 'self'
When the specification is finalized, the X- will be dropped, and it will simply be 'Content-Security-Policy'.
A call for supportHi Developers! Start implementing this feature! It's important for the future and security of the web. The web's biggest vulnerability, from what I understand, is still XSS, but if people start to properly implement CSP, XSS can effectively be a thing from the past.
So even if you don't want to risk using CSP on a production environment, at least consider adding the headers in your development environment. It will force you to write better code, by not embedding javascript directly into the html source. By considering this right now, you will also make it much easier if you do decide to adopt CSP at some point in the future.
I'm implementing CSP full-on in a new project, and one of the things I've noticed already is that some of the javascript we embed from 3rd parties use eval() and inline html events (onclick & friends). For the sake of security we will most likely decide to only use 3rd party code if they are indeed CSP-compatible.
A quick update about CSP. Browsers are well on their way to all adopt the specification.
An early draft was already adopted by Firefox 4, and I just found out that it's also working in Chrome, Safari and IE 10.
IE10 and FF are using the following header:
- X-Content-Security-Policy: default-src 'self'
While Safari and Chrome use:
- X-Webkit-CSP: default-src 'self'
When the specification is finalized, the X- will be dropped, and it will simply be 'Content-Security-Policy'.
A call for supportHi Developers! Start implementing this feature! It's important for the future and security of the web. The web's biggest vulnerability, from what I understand, is still XSS, but if people start to properly implement CSP, XSS can effectively be a thing from the past.
So even if you don't want to risk using CSP on a production environment, at least consider adding the headers in your development environment. It will force you to write better code, by not embedding javascript directly into the html source. By considering this right now, you will also make it much easier if you do decide to adopt CSP at some point in the future.
I'm implementing CSP full-on in a new project, and one of the things I've noticed already is that some of the javascript we embed from 3rd parties use eval() and inline html events (onclick & friends). For the sake of security we will most likely decide to only use 3rd party code if they are indeed CSP-compatible.
A quick update about CSP. Browsers are well on their way to all adopt the specification.
An early draft was already adopted by Firefox 4, and I just found out that it's also working in Chrome, Safari and IE 10.
IE10 and FF are using the following header:
- X-Content-Security-Policy: default-src 'self'
While Safari and Chrome use:
- X-Webkit-CSP: default-src 'self'
When the specification is finalized, the X- will be dropped, and it will simply be 'Content-Security-Policy'.
A call for supportHi Developers! Start implementing this feature! It's important for the future and security of the web. The web's biggest vulnerability, from what I understand, is still XSS, but if people start to properly implement CSP, XSS can effectively be a thing from the past.
So even if you don't want to risk using CSP on a production environment, at least consider adding the headers in your development environment. It will force you to write better code, by not embedding javascript directly into the html source. By considering this right now, you will also make it much easier if you do decide to adopt CSP at some point in the future.
I'm implementing CSP full-on in a new project, and one of the things I've noticed already is that some of the javascript we embed from 3rd parties use eval() and inline html events (onclick & friends). For the sake of security we will most likely decide to only use 3rd party code if they are indeed CSP-compatible.
It used to be that once a year I would take a good, hard look at the tools I used and endeavor to learn something new or change my workflow with those tools. However, I’ve been living the #startuplife for the past two years, so it’s been about three years since I last addressed my development toolchain. I decided to come up for air and take some time this weekend to rectify that by addressing five main areas: my terminal emulator, my shell, my terminal multiplexer, my IRC client, and my color scheme—yes, even my color scheme! In addition, I decided to push out my updated Octopress-powered blog, even though things are still a little rough around the edges.
Switching to iTerm2I’ve been a long-time user of Terminal.app, but I had been hearing good things about iTerm2. I actually used iTerm (version 1) years ago, but I switched back to Terminal.app for reasons I cannot recall. Nevertheless, iTerm2 has come a long way, and I wanted to take advantage of some of its functionality like split panes, better full-screen support, etc. So, that was the first major change I made to my tools.
Ditching bash for zshBash has been my favored shell since I began using Linux about fourteen years ago. I’d never given much thought to using a different shell, and to be honest, switching shells always seemed a daunting task. I thought I’d have to relearn my way around the shell, and everything I took for granted with Bash would be non-existent in a different shell. Fortunately, this is not true. As it turns out, zsh “can be thought of as an extended Bourne shell with a large number of improvements, including some features of bash, ksh, and tcsh” (Wikipedia).
I was able to switch to zsh without ditching my knowledge of bash. As a result, I’ve gained all the advantages of zsh, which include advanced customization and scripting capabilities, while continuing to provide most (if not all) the same functionality and commands I’m used to in bash. I have much more to learn, though, so if you have tips and tricks, please share.
If you’re interested in switching to zsh, I recommend checking out oh-my-zsh. It’s a framework for managing your zsh configuration, and it contains lots of goodies. In addition, there are great posts by Mark Nichols and Jon Kinney that will get you quickly up-to-speed with oh-my-zsh. The latter post has the awesome title “It’s not enough to bash in heads, you’ve got to bash in minds…with ZSH”.
Using tmux instead of screenGenerally, I’ve really only used screen when I started noticing that my connection to a remote development machine was getting sluggish or I wanted to keep a constant connection to IRC, but tmux has opened my eyes to so many more possibilities that a multiplexer can offer. I’ve just only started using it, so I can’t say much about it, but I encourage you to read Hawk Host’s two-part post on tmux.
Moving back to irssiI used irssi in a screen session for years. Then, I decided I needed Growl notifications from my IRC client. I quit using irssi in favor of Linkinus. I’ve used Linkinus for about two years—together with the IRC bouncer znc for some of that time—but I’ve continued to miss the flexibility and functionality of irssi. On a whim, I decided to switch back to irssi, but it wasn’t without so
Truncated by Planet PHP, read more at the original (another 3132 bytes)
Sublime Text 2 is a new cross-platform text editor that I’ve recently switched to. It’s still in public beta, but already offers better performance (and battery life!) and a better look (fonts that render properly!) than Java-based IDEs such as Netbeans.
One thing it didn’t have was support for PHPUnit, so I’ve made a plugin. It’s available to install via Package Control.
You Need A phpunit.xml or phpunit.xml.dist FileTo use this plugin, your project needs to contain either a phpunit.xml or a phpunit.xml.dist file. This file contains all the configuration that needs to be passed to PHPUnit. The plugin searches upwards from your code, and will favour a phpunit.xml file over a phpunit.xml.dist file if it finds both.
If you don’t have one, you need to go and create one now.
How To UseIf you have your code open in a Sublime Text 2 window, right-click inside the window to see what your options are:
This option appears if the PHPUnit plugin can find your unit tests. It takes the name of your class, and uses the standard PSR-0 transformation to figure out what the name of your test file should be.
For example, if your class is called ‘Phix_Project\CommandLineLib\CommandParser.php’, the PHPUnit plugin will search for a file ‘CommandLineParserTest.php’ that’s in a folder called ‘Phix_Project/CommandLineLib’.
Again, this option only appears if the PHPUnit plugin can find your unit tests.
This option just points PHPUnit at your phpunit.xml or phpunit.xml.dist file.
If you have your tests open in a Sublime Text 2 window, right-click inside the window to see what your options are:
If you’re someone who prefers keyboard over mouse, then you’ll probably want to run the PHPUnit plugin commands from Sublime Text 2′s Command Palette:
You get the same commands that appear on the right-click menu … the right commands will appear for the file that you’re currently editing, just as you’d expect.
Finally, you can also right-click on your phpunit.xml (or phpunit.xml.dist) file in the Project Sidebar, and run your unit tests using that specific config file.
Helpful SnippetsLike TextMate before it, Sublime Text 2 also has a handy snippets feature, where it can insert a pre-crafted block of text (or, in our case, PHP code) to speed up your coding. I’m collecting most PHP-related snippets in my Additional PHP Snippets plugin (hat-tip to Rob Allen for the inspiration for this), but the PHPUnit plugin includes a few PHPUnit-related snippets to help.
I find this handy mostly so that I don’t have to remember which class my test class has to extend :)
Truncated by Planet PHP, read more at the original (another 664 bytes)
With the release of Zend Framework 1.8 came the long awaited component for bootstrapping a Zend Framework application. Many different bootstrapping-solutions became obsolete with Zend_Application.
In the beginning of the framework most developers didnt give much thought on bootstrapping. Most of the initialisation work was done directly in index.php, the central starting point of the application. Teams often moved that bootstrapping code to a separate configuration script. The solution worked, but many people wanted a more standardised process for application initialisation.
This blog posting is in German as the event it relates to is German-only.
Sorry for the inconvenience.
Bei allen PHP-Themen zählt nichts mehr als die Praxis. Deshalb bieten wir unsere Power-Workshops interaktiv und mit intensivem Praxisbezug an. Über die behandelten Themen entscheiden die Teilnehmer mit ihren konkreten Fragen. Anstelle von Frontalunterricht erleben sie die Entwicklung von neuem Code unmittelbar. Mit Augenzwinkern und Spaß erläutern Sebastian Bergmann, Arne Blankerts und Stefan Priebsch Entwicklungsmethoden und Tools und stellen Trends und Konzepte vor.
Der nächste PHP Summit findet im März in München statt. Und das sind die Workshops:
Update PHP: Neue Features und Technologien nutzen Workshop von Sebastian BergmannPHP 5.3 und PHP 5.4 überzeugen im Programmieralltag durch eine Fülle relevanter Vereinfachungen. Lernen Sie die innovativen Features und geschickte Einsatzmöglichkeiten der neuen Versionen kennen. Entdecken Sie das Lösungspotenzial aktueller Technologien aus dem PHP-Umfeld (memcached, ZeroMQ ) für Ihre Fragestellungen.
Weg mit Strubbelcode: identifizieren verbessern vermeiden Workshop von Sebastian BergmannFrüher oder später wird unsauber geschriebener Code zum Ärgernis. Nicht nur für den, der ihn warten muss. Änderungen und Erweiterungen können im Extremfall den Code unwirtschaftlich machen. Lernen Sie schlechten Code durch statische Codeanalyse aufzufinden und in test- und wartbaren Code umzuschreiben. Lernen Sie mithilfe der SOLID-Prinzipien, nachhaltig wartbaren Code zu schreiben.
Best Practices aus dem Alltag für den Alltag Workshop von Arne BlankertsNatürlich könnte man das Rad jeden Tag neu erfinden. Meist fehlt dafür die Zeit, Spaß macht es auch nicht und Fehler können sich so immer wieder an denselben Stellen einschleichen. Für die vielen alltäglichen Probleme, die nur geringfügig von schon vorhandenen Lösungen abweichen, gibt es clevere Ansätze, die das Leben leichter machen. In einer komplett vom Auditorium gesteuerten Live Session zeigt der Workshop dafür programmatische Konzepte und lädt zur Diskussion über Tools und klassische Fragestellungen ein.
Auf Fehler sicher vorbereitet sein Workshop von Arne BlankertsProgramme und Webseiten enthalten Fehler. Immer. Sie werden sichtbar, wenn Benutzer falsche, ungültige oder unerwartete Eingaben machen, der Zugriff auf die Datenbank plötzlich unmöglich ist oder die Festplatte überläuft. Um solche und andere Probleme sicher abzufangen, gibt es verschiedene Ansätze, die hier vorgestellt und diskutiert werden. Wie man Exceptions richtig anwendet, warum ein eigener Error Handler hilfreich ist und dass Debugging viel mit Sicherheit zu tun hat, vermittelt der Workshop lebendig und anschaulich.
Objektorientierte Programmierung (OOP) in PHP I: Basiswissen Workshop von Stefan PriebschDer Workshop klärt die Frage, was es mit der objektorientierten Programmierung eigentlich auf sich hat. Jenseits der bekannten Standardbeispiele führt er praktisch in die OOP mit PHP ein. Dabei werden neben den Grundlagen und zentralen Prinzipien der OOP interessante Features beispielsweise aus der Standard PHP Library (SPL) vorgestellt und ihr sinnvoller Praxiseinsatz vorgeführt. Neben Faktenwissen wird eine Denkweise vermittelt, die es erlaubt, unnötig komplizierte Ansätze von vornherein zu umgehen.
Objektorientierte Programmierung (OOP) in PHP II: Aufbauwissen Workshop von Stefan PriebschDer Workshop zeigt Teilnehmern, die mit den Grundlagen der OOP vertraut sind, fortgeschrittene Techniken wie Dependency Injection, abstrakte Klassen, Interfaces und Best Practices für erfolgreiche OOP. Eine Live-Coding-Session macht den Einsatz der vorgestellten Techniken in der Praxis erfahrbar. Außer Faktenwissen zeigt der Workshop, dass gute Lösungen einfache Lösungen sind: Einfache Objekte sind leichter wieder zu verwenden und vermeiden Fehler.
PHP-Anwendungen testen: Basiswissen Workshop von Sebastian BergmannDer Workshop vermittelt grundlegende Kenntnisse und Fähigkeiten im Einsatz von PHPUnit bei Unit Tests, Datenbank-Interaktionstests, Edge-to-Edge- Tests und End-to-End-Tests. Sie lernen alles, was Sie über das Schreiben, Ausführen und Organisieren von Unit Tests mit PHPUnit beherrschen müssen.
PHP-Anwendungen testen: Aufbauwissen Workshop von Sebastian BergmannPHPUnit clever einsetzen: Die Teilnehmer lernen die besten Praktiken beim Einsatz von PHPUnit und erprobte Strategien bei der Einführung von Testmaßnahmen an vorhandener So
Truncated by Planet PHP, read more at the original (another 6664 bytes)
The past weeks I finally had some time to invest in the DMS library again, so i got busy with a few things. I also had to fix a big problem which had gone unnoticed to me, so i have to thank Mr. Guilherme Blanco for pointing it out.
Sadly this means a BC break, so please follow and make adjustments.
The BC break: ->filter() becomes ->filterEntity()The reasoning here is simple, PHP still supports legacy from PHP4 meaning a function with the same name as the class is understood as a constructor. This generates a few nasty notices, and it made enough sense to rename the function, making it clear like the other ones.
The DMSFilterBundleAlong with this i had time to work on building a Bundle so you can plug filtering into Symfony 2 just as you would with validation.
Composer supportThis bundle is also available on Packagist, making it easy to install, i'll also add the DMS and Filter library as standalones to this soon.
TagsI finally tagged the releases as 1.0, or rather 1.0.1 as i quickly found a few fixes to put in.
The rest remains, here are the links:
DMS Library: github
DMS Filter Library (sub-tree split): github
DMS Filter Bundle (sub-tree split): github | packagist/composer | knpbundles page (please recommend it if you like it)
© Rafael Dohms for Rafael Dohms, 2012. |
Permalink |
No comments
Want more on these topics ? Browse the archive of posts filed under PHP.
So this post is a bit of a rant more than anything, so for the three regular readers of this blog feel free to skip over this post. I promise to make this foray a brief one.
I made a blunder on my flight home from Atlanta to Akron/Canton Airport a few weeks ago; I left my lovely, SugarCRM logo and my name engraved iPad safely in it’s case in the seat pocket of seat 3A. D’oh!
I realized this the moment I got home, and being a bit of a snow storm decided it not prudent to risk life and limb to return to the airport. Calling the airport informing them of this, they took my name and number as said they would ask the Delta desk about this. Being my self driven self, I started tracing the plane, and saw it was doing a CAK-ATL-CAK-ATL-OMA run that day, so figured it would end up in one of CAK, ATL, or OMA ( Omaha for those who aren’t as familiar with airport codes ).
So I went back to the airport at CAK, and they didn’t have it ( but had another iPad someone lost on a plane ), and called OMA, which didn’t see it either. My guess is that it’s in ATL, but low and behold, THERE IS NO NUMBER TO CALL ABOUT DELTA LOST AND FOUND AT ATLANTA. That’s right, nobody to call and ask, nor anyone I could be transfered to that will call there and ask. What do they want you to do? Fill out a web form and hope for the best. Which I did, and all I am left with is hope
.
So my call to the blogosphere and twittersphere is this: short of going down to Atlanta and stalking the Lost and Found desk, who can I call to help me.
This is the third installment in my series about writing a RESTful web service in PHP (the previous entries are about understanding the request and routing it. It is probably the last one but there are a few other things I'd like to cover such as error handling, so I might keep adding to it, especially if I get any particular requests or interesting questions in the comments. So far we've covered parsing requests to determine exactly what the user is asking for, and also looked at routing to a controller to obtain the data or perform the action required. This post gives examples of how to return the data to the client in a good way.
Output Handlers Instead of ViewsWe'll have as many output handlers as we have supported output formats. The joy of having all the controllers return the data to index.php is that we can then add common output handling to all the data. In our example system, we can remove that ugly print_r from index.php and instead detect which output format is needed and load the relevant view. My code looks like this:
$view_name = ucfirst($request->format) . 'View';
if(class_exists($view_name)) {
$view = new $view_name();
$view->render($result);
}
The most simple example is a JsonView which looks like this:
class JsonView extends ApiView {
public function render($content) {
header('Content-Type: application/json; charset=utf8');
echo json_encode($content);
return true;
}
}
As you can see here, it's pretty simple! We send the Content-Type header first to let the consumer know what's in the response, then we just encode the JSON and echo it out.
To support other formats, you might loop over your array (remember it might be nested – things usually get recursive at this point for something like an XML format) and transform it into the new format. Between two PHP systems, it might be simpler to support s
Truncated by Planet PHP, read more at the original (another 2815 bytes)