PHP Summit in MĂŒnchen
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 Bergmann
PHP 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 Software kennen. Anhand zahlreicher Beispiele entwickeln Sie einen Blick fĂŒr schlechte Tests und lernen, sie zu verbessern, schwer testbaren Code zu identifizieren und Legacy-Code Schritt fĂŒr Schritt testbar zu machen.
Geheimtipp XML: Die smarte Art der Anwendung Workshop von Arne BlankertsXML ist das Standardformat fĂŒr den Datenaustausch im Web und verbirgt sich in vielen, fĂŒr Endanwender oft nicht sichtbaren Dateiformaten (z. B. aktuelle MS-Office-Versionen) und Formen. Der Workshop zeigt, dass XML richtig SpaĂ machen kann, wenn die ĂŒbermittelten Daten validiert werden und der Zugriff mit effiziente APIs erfolgt. In der Live Session erweitern wir das DOM-API von PHP um eigene Methoden und unterstĂŒtzen die Lokalisierung durch PHP. Eigene XSD Schemas zur Validierung werden definiert und der Einsatz von XPath als Abfragesprache vorgefĂŒhrt. Vermittelt wird auch der Einblick in eine wirklich effektive Fehlerbehandlung.
Neu: Tuning fĂŒr Web-Anwendungen Workshop von Arne BlankertsWer einen ungeschickten Weg zur Lösung beschreitet, handelt sich Probleme ein, die er gar nicht haben möchte. In der Regel geht das zulasten des Tempos und der Skalierbarkeit. Wie man solche Schwachpunkte in gĂ€ngigen Aufbauten und Architekturen vorab erkennt und durch bessere Konzepte von vornherein vermeiden kann, zeigt dieser Workshop an zahlreichen Praxisbeispielen. Eigene Denk- und Herangehensweisen können ĂŒberprĂŒft und modifiziert werden.
Entwurfsmuster I: Die wichtigsten Standards Workshop von Stefan PriebschWarum das Rad jedes Mal neu erfinden? Die Teilnehmer lernen in diesem Workshop wichtige Entwurfsmuster kennen, die sich in PHP-Webanwendungen besonders bewĂ€hrt haben. HĂ€ufig in der Praxis auftretende Schwierigkeiten werden vorgefĂŒhrt und Lösungen werden live programmiert. Vor- und Nachteile sowie Einsatzmöglichkeiten und typische Fehler bei der Anwendung von Standardmustern werden ausfĂŒhrlich erlĂ€utert und diskutiert.
Entwurfsmuster II: Integration anspruchsvoller Patterns Workshop von Stefan PriebschDer Workshop behandelt Themenstellungen wie temporale Patterns, das Speichern von Objekten in relationale und NoSQL-Datenbanken oder Enterprise Integration Patterns mit Schwerpunkten, die von den Teilnehmern frei festgelegt werden. Eine Reihe typischer Probleme wird vorgefĂŒhrt und analysiert. Die zu ihrer Lösung eingesetzten (wenig bekannten) Entwurfsmuster vermitteln den Teilnehmern fortgeschrittene Kenntnisse, die im Alltag wertvoll sind.
Moderne Versionskontrolle mit Git Workshop von Sebastian BergmannGit ist ein mĂ€chtiges Versionsverwaltungssystem, mit dem Sie alle Bestandteile Ihrer Software durch alle Ănderungen und Versionen zuverlĂ€ssig verfolgen können. Damit schaffen Sie die Grundlage fĂŒr die kontinuierliche Integration der Software. Der Workshop vermittelt Grundlagen fĂŒr den Einsatz von Git, Best Practices und Prozesse fĂŒr Entwicklung, Release-Management und Deployment, die Ihre Teamarbeit spĂŒrbar effektiver machen.
Kontinuierliche Integration mit Jenkins Workshop von Sebastian BergmannWer die QualitĂ€t seiner Software wĂ€hrend der Entwicklung und im Betrieb messen und kontrollieren will, profitiert vom Einrichten einer Umgebung, in der PHP-Projekte kontinuierlich integriert werden können. Mit der Kombination dynamischer und statischer Testverfahren automatisieren Sie wiederkehrende Aufgaben, sind ĂŒber die SoftwarequalitĂ€t auf dem Laufenden und minimieren Projektrisiken erfolgreich. Der Workshop vermittelt die Grundlagen der kontinuierlichen Integration und Inspektion von PHP-Software. Sie ĂŒben Installation, Konfiguration und Betrieb von Jenkins fĂŒr PHP-Projekte.
Am besten mit dem Schlimmsten rechnen! Workshop von Arne BlankertsIn Zeiten stĂ€ndiger Einbruchsversuche durch gelangweilte Anwender ergibt es Sinn, wirklich immer mit Angriffen aus dem Internet zu rechnen. Auch vermeintlich sichere Strukturen bieten versierten Hackern oft keinen nennenswerten Widerstand. Verantwortungsbewusste Entwickler mĂŒssen wissen, wie man der eigenen Anwendung oder Infrastruktur schaden könnte. Der Workshop vermittelt grundlegende ZusammenhĂ€nge und zeigt in einer Live Session, was Begriffe wie XSS, CSRF oder SQL-Injection bedeuten, wie man Angreifern das Leben schwer macht und wirksame Lösungen implementiert.
Attacke! Was Angriffe im Web erfolgreich macht Workshop von Arne BlankertsAnwendungen sind im Internet permanent Angreifern ausgesetzt. Im Workshop wechseln die Teilnehmer die Seiten und greifen selbst eine Demo-Blackbox-Anwendung an. Sie lernen, wie Angreifer Informationen sammeln, SicherheitslĂŒcken ausnutzen und Server ĂŒbernehmen. Vermittelt werden Methoden, um LĂŒcken zu finden, sie zu schlieĂen und Angriffe abzufangen. Der abschlieĂende Blick in den Quellcode sensibilisiert fĂŒr Schwachstellen und zeigt, wie man sie behebt.
Framework: Basics in drei Stunden Workshop von Stefan PriebschGrundlegende Fragen nach der Struktur einer Webanwendung und dem Schreiben von Code, der test-, wart- und erweiterbar ist, werden an einem praktischen Beispiel beantwortet. Wichtige Entwurfsmuster und Best Practices werden vorgefĂŒhrt. Feedback und Fragen der Teilnehmenden steuern den Verlauf der Session. Ziel ist ein besseres VerstĂ€ndnis fĂŒr die wesentlichen Konzepte von Frameworks.
Warum der Turm in Pisa schief steht Workshop von Stefan PriebschNichtfunktionale Aspekte werden in ihrer Bedeutung fĂŒr technische Entscheidungen oft unterschĂ€tzt oder ganz ĂŒbersehen. Je komplexer die Fragestellungen desto wahrscheinlicher ist es, dass aus diesem Wegschauen Probleme resultieren, die spĂ€ter nicht leicht einzufangen sind. Wer sich vor der Entwicklung Gedanken zur Architektur macht, löst heute Probleme von morgen. Der Workshop zeigt Architekturmuster fĂŒr Webanwendungen und geht auf aktuelle Trends wie Distributed Caching, Message Queues und NoSQL ein. Es werden erprobte Bausteine vorgestellt, mit denen hochperformante und skalierbare Webanwendungen in PHP entwickelt werden können.
Der PHP Summit bietet effizientes Lernen in entspannter AtmosphÀre. Profitieren Sie von dieser einzigartig intensiven Form der Informationsvermittlung mit einem unschlagbaren Preis-Leistungs-VerhÀltnis und reservieren Sie sich Ihren Platz noch heute!
Jeremy Cook's Blog: Implementing the ArrayAccess Interface
Jeremy Cook is back with the next part of his series looking at the handy features PHP's SPL provides. In this new post he looks at the ArrayAccess interface and how it can make your data more accessible to PHP's own array handing functions.
ArrayAccess allows you to treat an object that implements it as if it is an array for the purposes of setting, unsetting and retrieving data from it. Please note the emphasis in the last sentence! ArrayAccess does not make an object behave like an array in any other way. If you pass an object that implements ArrayAccess to a PHP array function such as in_array() you'll still get an error. This will become a little clearer with some of the examples below.He shows what you'll need to use this interface in your class - implementing the interface and defining a set of four methods to get/set and check for the value in your array. He includes a practical example of pulling data back from an API and wrapping it in a class to make accessing it simpler (also implementing the Countable interface as well, see the previous post for more on that). Code is include to illustrate how it can be used.
Leaseweb Labs Blog: POC: Flexible PHP Output Caching
On the Leaseweb Labs blog there's a recent post looking at using the POC framework to work with flexible output caching. The tool makes it easy to create a new object and push cache content into it, automatically caching the data to sources like the file system, a Redis instance or a MongoDB database.
Last year at the Symfony conference in Paris I have heard a really good quote: "There are only two hard things in Computer Science: cache invalidation and naming things" - Phil Karlton. I agree with it and it gave me a boost to keep evolving the concept.He includes an introduction to the caching features of the framework complete with sample code showing first how to cache to the default file system and a more complex example that uses unique caches and page blacklists. Other features planned for the caching tool include edge-side includes, using Twig for templating and statistics recorded to a database.
LearnComputer.com: PHP Training: Online vs. Classroom
On the LearnComputer.com site there's a new post comparing the benefits/downfalls of online versus classroom learning of PHP development. They list a few advantages and disadvantages of each.
There can be many factors in the decision to learn PHP online or to take a class in-person, and for some, this can be a difficult decision to make. This article discusses the pros and cons of each method of PHP training to help you find the learning method that is going to suit your needs best. PHP isn't a new programming language, and there is a wealth of information on it on the web for every level of proficiency. The question is whether these resources alone are sufficient to get you up-and-running with PHP quickly.For the "online" section advantages include flexible schedules and more up to date content. The disadvantages are things like a prerequisite knowledge of using computers/the training software and that the instructor might only have "set hours" to answer questions and offer help. The "classroom" option advantages include the motivation of a regular meeting time and fewer technology hurdles to overcome. Disadvantages include the need for a time/in-person commitment and that the focus might be higher level than needed to appeal to a more mass audience.
AndroidHive: Android Login and Registration with PHP, MySQL and SQLite
On the AndroidHive site there's a recent tutorial (plus screencast) about combining PHP, MySQL and SQLite to act as the backend authorization for your Android application.
In my previous article Android Login and Registration Screen Design i explained designing the login and registration interfaces, but it has no functionality. In this tutorial i am explaining how to build complete login and registration system in android using PHP, MySQL and SQLite. Also this tutorial covers how to build simple API using PHP and MySQL.The tutorial walks you through each step of the process:
- Creating MySQL Database and Tables
- Building PHP API Classes
- Starting Android Project
- Making the JSON Parser, SQLite Database Handler and User Functions Classes
- Designing the Screens
- Switching between Activities
- Finally Updating AndroidManifest.xml
If you want to get started quickly, you can just download the final result and go.
Script-Tutorials.com: Form Validation with Javascript and PHP
On the Script-Tutorials.com site today there's a new tutorial about form validation using a combination of jQuery on the frontend and PHP on the backend.
In this tutorial, I will show you how to create an attractive, pleasant to look form for your website and then I will explain you how to dynamically validate them using Javascript. We'll also cover server-side validation with PHP to make everything 100% safe. This tutorial will help you to add more functionality to your forms which leads to better user experience and better quality of your website.His sample form (name, password, email and gender) is made from some pretty simple HTML markup. The real trick comes with the jQuery validation on each field handled in an onKeyUp. Included are both a "password strength" method and an email validation method to check the format of the address. Errored fields have their background color changed to indicate that they've failed and some basic validation (length, password match, etc.) are also included. The PHP does much of the same validation once the form is posted and returns any error messages that might have come up.
You can download the code or try out a live demo to see the scripts together in action.
PHPMaster.com: Where on Earth are You?
In PHPMaster.com's latest tutorial Lukas White introduces you to using the Yahoo "Placemaker" web service to geographically locate a place from a free-form text string. The results include "place details" like the type of the location, latitude, longitude and how confident they are in their match.
The challenge then is to do two things: work out what place you could be talking about, disambiguate if necessary, and then identify exactly where on Earth that is. That's what I'll show you how to do in this article; by using a freely available web service, we'll write a simple program to ask users where they are (and ask them to clarify if necessary) before identifying their responses in concrete terms.He shows how to make a request to the Placemaker web service, passing it a string coming from the user, to be located. The POST request contains a few pieces of data including an application ID , your desired output type and the language you're using for the input. His example code uses curl to make the request and handles it (the XML response at least) with a call to simplexml_load_string.
Site News: Blast from the Past - One Year Ago in PHP
- Chris Hartjes' Blog: Book Review: PHP 5 Social Networking
- Rob Allen's Blog: Zend Framework 2 in Action
- Mike van Riel's Blog: Introducing: DocBlox
- SocialDevelopers.net: Facebook and the Zend Framework - Part 1: Iframe Authentication
- Binpress.com: Web Developer Programming Contest
- Matthew Weier O'Phinney's Blog: Why PHP Namespaces Matter
- Michael Feichtinger's Blog: PHP5 WebSocket Example - A Simple Chat
- Greepit.com: Behavior Driven Development Framework for PHP: Behat
- CodeIgniter.com: CodeIgniter 2.0.0 Released
- Steve Francia's Blog: On Symfony2
- Joshua Thijssen's Blog: Password hashing and salting
- Volker Dusch's Blog: Setting up Jenkins for PHP Projects
- InfoWorld: InfoWorld review: Fabulous PHP frameworks
- Strattonbrazil's Blog: php to python: Why PHP is now dead to me
- Gonzalo Ayuso's Blog: Function decorators in PHP with PHPDoc and Annotations
FFmpeg: A beginners guide â part 2
Continuing the last post on FFmpeg, here we will discusses various fundamental tasks you can accomplish with the audio stream in FFmpeg.
2.1.1 Introduction to TranscodingOne of the basic tasks you can perform on an audio track in FFmpeg is to convert it into another format. This process known as Transcoding, is the direct digital-to-digital conversion of one stream encoding to another, whether video or audio. Transcoding is usually done in cases where a target device â media player such as iPod, iPAD, DVD players or a software application, does not support the format or has limited storage capacity that requires a condensed file size. Transcoding can also be used to convert an incompatible or obsolete format to a better-supported format.
Transcoding is generally a âlossy processâ – a data encoding method which compresses data by discarding (losing) some of it to minimize the amount of data that need to be stored in a file; however, transcoding can also be âlosslessâ if the input is losslessly compressed and the output is either losslessly compressed or stored in a uncompressed state. Although compression can reduce file size considerably, repeatedly performing transcoding on a single file using lossy compression can create a âgeneration lossâ â a reduction in the quality of the audio when copying, which would cause further reduction in quality on making a copy of the copy. So you need to keep this in mind while repeatedly transcoding between various formats.
Although I could not show you here the difference between an original and lossy audio compression (due to the limitation of the media of course), the following shows an example of a lossy compression in an image. The original JPG image is on the left and a lossy image of the same after repeated compression is shown on the right. As we lose precious information forever during compression, we cannot get back the original image using the compressed image.
2.1.2 Audio compressionAudio compression is a form of data compression designed to reduce the transmission bandwidth and storage requirement of a digital audio stream. Audio compression algorithms are implemented in software as audio codecâs, – which is a software program or library capable of encoding/decoding a digital audio stream.
Audio compression is either lossy or lossless as discussed earlier. Lossless audio compression produces a version of digital audio that can be decoded to an exact digital duplicate of the original audio stream. This is in contrast to the irreversible changes upon playback from lossy compression techniques such as Vorbis and MP3.
The whole idea behind audio compression in FFmpeg is to lower the audio bitrate (96kbps, 128kbps, 192 kbps etc.), this effectively also reduces the fidelity or quality of the audio. So you want to keep in mind that, a high bitrate audio file confirms a better sound quality, so by lowering its bitrate you are actually degrading the quality.
For normal computer use, the 128kbs rate produces a quality equal to that of an audio CD. But in the case of an MP3 use, it is necessary to use a 256kbs bitrate to reach an identical result to that of the CD quality sound.
Now that we have gone through a short introduction to compression, we will now work on the process of transcoding audio files.
To run the example commands in this section, you will need an audio file in a .wav or an .mp3 format. You can get hold of a wav file by ripping an audio track from a music CD or downloading an mp3 file from the Internet. Call the resulting file âmyaudio.mp3â. For this section I used the âSolo Piano 7â Opening file from http://www.archive.org/details/solo-piano-7.
Next, we will get ffmpeg to identify the file. This will tell us the various details of the audio file. The simple way to get this information is to just tell ffmpeg to use it for input. For this we need to use the âi option. Enter the following command at your prompt.
ffmpeg -i myaudio.mp3
The exact output on my PC is shown below; which may differ from yours depending on the version of ffmpeg you are using.
D:\ffmpeg>ffmpeg -i myaudio.mp3
ffmpeg version N-31100-g9251942, Copyright (c) 2000-2011 the FFmpeg developers
Input #0, mp3, from ‘myaudio.mp3′:
Metadata:
album : solo piano 7
artist : Torley
album_artist : Torley
composer : Torley
genre : Piano
track : 001/176
title : 001 â Openings
date : 2008
Duration: 00:01:39.50, start: 0.000000, bitrate: 193 kb/s
Stream #0.0: Audio: mp3, 44100 Hz, stereo, s16, 192 kb/s
At least one output file must be specified
There is a lot of information we can gather from the output – the track is
1 minute 39.50 seconds long, the bitrate is 193kb/s, the audio is encoded in mp3 format at 44100Hz (44.1KHz) and has two channels (stereo). All this information will come in handy during a transcoding process.
Let us now convert the downloaded file to a simple wav format. Notice that we have not specified any format option or flag, just the complete output filename. FFmpeg automatically guesses which encoders to use by noticing the format of the input and output files, this can be a big help if you keep forgetting the option name or are just being lazy. If you are not going to specify the encoder format, make sure you mention the full filename, along with the appropriate format extension.
ffmpeg -i myaudio.mp3 myaudio.wav
The output of the command is shown below.
ffmpeg version N-31100-g9251942, Copyright (c) 2000-2011 the FFmpeg developers
Input #0, mp3, from ‘myaudio.mp3′:
Metadata:
album : solo piano 7
artist : Torley
album_artist : Torley
composer : Torley
genre : Piano
track : 001/176
title : 001 – Openings
date : 2008
Duration: 00:01:39.50, start: 0.000000, bitrate: 193 kb/s
Stream #0.0: Audio: mp3, 44100 Hz, stereo, s16, 192 kb/s
File ‘myaudio.wav’ already exists. Overwrite ? [y/N] y
Output #0, wav, to ‘myaudio.wav’:
Metadata:
album : solo piano 7
artist : Torley
album_artist : Torley
composer : Torley
genre : Piano
track : 001/176
title : 001 – Openings
date : 2008
encoder : Lavf53.4.0
Stream #0.0: Audio: pcm_s16le, 44100 Hz, stereo, s16, 1411 kb/s
Stream mapping:
Stream #0.0 -> #0.0
Press [q] to stop, [?] for help
size= 17141kB time=00:01:39.50 bitrate=1411.2kbits/s
video:0kB audio:17141kB global headers:0kB muxing overhead 0.000251%
Notice how large the resulting wav file is (17 Mb) as compared to the original mp3 format (2.1 Mb). This being for the reason that the wav file is not compressed like its mp3 counterpart. Incidentally, the audio format of the wav is Pulse-code modulation (PCM), technically PCM signed 16 bit little-endian format.
As you can see from the screenshot above the output of an ffmpeg command is quite large, so from here on Iâll just specify the command and do away with the output screen unless it is required for explanation.
2.1.5 Changing the bitrate of the audioAs we learned in Chapter 1, bitrates control the file size and the quality of an audio or video stream. Lowering the bitrate will result not only in a reduced file size but also diminish the quality of the final output. This can be required if you have a high quality audio recording and need to lower the quality for a reduced file size to stream over the Web. For example the following command will set the bitrate of the mp3 file to 64kb/s. This uses the âab option to the job.
-ab
ffmpeg -i myaudio.mp3 -ab 64k out.mp3
The higher the value the better is the audio quality. This is one of the important factors responsible for the audio quality. But that doesn’t mean you can make a poor audio file sound better by increasing its bitrate. The resultant file will just be of bigger size.
Another example – to transcode an mp3 file to an AAC format, with a bitrate of 128K, we can use the following.
ffmpeg -i myaudio.mp3 -ab 128k myaudio.aac
As we saw earlier the original audio track has 2 channels (stereo). Many times it is not necessary to have 2 channels, like in a speech recording, where its really doesnât matter.. In such cases you can further reduce the file size by setting the audio channels to mono or â1â. For output streams it is set by default to the number of input audio channels.
-ac
ffmpeg -i myaudio.mp3 -ac 1 out.mp3
Note that once you convert a stereo channel to a mono, you cannot convert it back to a stereo channel audio. That information is lost forever. The same thing happens with bitrates. Once you reduce a bitrate of an audio file, you cannot just increase the bitrate back again to get the original quality. That information is already gone. So as a precaution, never work with your original media files. Make a copy of the original and work with the copy.
The other important audio option is âacodec. This option lets you choose the type of audio codec you want to use. e.g. if you are using ffmpeg on a mp3 file, then it will need the audio codec libmp3lame. You can specify it using -acodec libmp3lame. Although, by default, ffmpeg takes care of the codecs you need (by guessing it from the output file format) but if you need anything different, then go for this option. FFmpeg uses a default encoder for each audio stream, using the output file extension to guess the encoder to use. This option lets you force FFmpeg to use a specific audio encoder rather than the default. The following for example will extract the audio stream from a .flv video and save it as an .mp3 file using the libmp3lame encoder.
-acodec
ffmpeg -i myvideo.flv -acodec libmp3lame myaudio.mp3
Sometime you FFmpeg may be unable to correctly decode the input file, giving the error something like the following.
Error while decoding stream #0.0
In such cases you can force FFmpeg to use a particular decoder to decode the input file. The following example will force FFmpeg to use the mp3 codec toe decode the input file audio.
ffmpeg -acodec libmp3lame -i myvideo.flv myaudio.mp3
Note that the âacodec option comes before the âi option when we want the codec to apply to the input stream and comes after the âi option when we want the codec to apply to the output stream. To see what codecs are available on your system, issue the following command.
ffmpeg -codecs
Sometimes you may want to completely disable the audio recording for which we can use the âan option. This can be used to strip out an audio stream from a video file. When you use this option, all the other audio related attributes are cancelled out, which is fine, as they would not matter without the audio. So for example you are want to disable the audio from a video file and only copy the video stream, you can use the following.
ffmpeg -i myvideo.flv -an out.flv
Another important option is âar, the audio sampling frequency. This lets you set the maximum sampling frequency of the audio stream. Audio sampling was discussed in Chapter 1. You can use the option to reduce the sampling frequency to a lower value to reduce file storage or Internet bandwidth capacity. The default value is set at 44100Hz. The value is given in Hz. So the following will resample the input audio to 11025Hz with a single channel (mono).
-ar
ffmpeg -i myaudio.mp3 -ar 11025 -ac 1 myaudio.mp3
Note that once you have reduced the sampling frequency some of the audio data is lost. You cannot again resample it to a higher value and expect increase in the audio quality.
2.1.6 Audio grabbingUntil now we have looked into how to transform existing audio stream into other formats. FFmpeg can also grab audio from external devices such as a microphone. This can be useful if you need to record from your desktop microphone or create a screencast. Note that the following command will not work on a Windows machine. You need to have a Linux machine to correctly grab the mic audio. Enter the following command at your Linux prompt.
ffmpeg -f oss -i /dev/dsp ./audio.wav
This will start recording the input audio from the mic to the âaudio.wavâ file. Once started you will need to press âqâ to stop the recording. We will now look into the various options given above.
The option âf denotes the format to be used for the input stream. There are various formats FFmpeg supports; you can find the complete list by issuing the following command.
ffmpeg -formats
Here we are using the ‘oss’ format, which stands for Open Sound System input device. The Open Sound System (OSS) is an interface for making and capturing sound in Unix or Unix-like operating systems. In the Linux kernel, there have historically been two uniform sound APIs. One is OSS; the other is ALSA (Advanced Linux Sound Architecture). ALSA is available for Linux only.
The device â/dev/dspâ is the default audio input device in the Linux system. It’s connected to the main speakers and the primary recording source such as a microphone. The system administrator can set /dev/dsp to be a symbolic link to the desired default device.
The âaudio.wavâ file is where the recorded audio will be saved.
Another example – the following will record the mic audio to the file ârec.flacâ in the current directory, this is a flac format file.
ffmpeg -f alsa -ar 48000 -i front ./rec.flac2.2 Some popular audio formats
.AAC Advanced Audio Coding File – declared the new audio-file standard in 1997, designed to replace its predecessor, MP3. It provides better quality at lower bit rates, and its Appleâs standard iTunes and iPod audio format.
.AIF(F) Audio Interchange File Format – developed by Electronic Arts and Apple back in the â80s. AIFF files contain uncompressed audio, resulting in large file sizes.
.m4a Apple Lossless – This file format uses lossless compressions for digital music.
.MP3 MPEG Layer 3 – the most popular digital-audio music format, designed by a team of European engineers in 1991 to conserve the quality of a song while storing it in a small, compact file.
.OGG Ogg Vorbis – one of the most popular license-free, open-source audio-compression formats. Itâs efficient for streaming and compression because it creates smaller files than MP3 while maintaining audio quality.
.RA(M) Real Audio Media – developed by RealNetworks in 1995. It has a wide variety of uses, from videos to music, but is mainly used for streaming audio such as that from Internet radio stations.
.WAV Windows WAVE – IBM and Microsoft-developed format popular audio format among PC computer users; it can hold both compressed and uncompressed audio.
.WMA Windows Media Audio - designed by Microsoft to be an MP3 competitor, but with the introduction of iTunes and iPods, itâs fallen far behind MP3 in popularity.
2.3 Audio processing recipesMP3 to AAC High Quality Stereo
ffmpeg -i in.mp3 -acodec aac -ac 2 -ar 48000 -ab 192k out.aac
MP3 to AAC High Quality 5.1
ffmpeg -i in.mp3 -acodec aac -ac 6 -ar 48000 -ab 448k out.aac
Convert to low quality mp3 to preserve storage
ffmpeg -i in.mp3 -ab 64K out.mp3
MP3 to Vorbis OGG (can be played in HTML 5)
ffmpeg -i in.mp3 -acodec vorbis -aq 50 out.ogg
In the next post in the series we will look into various video processing tasks.
Subscribe now to get the next post update.
FFmpeg: A beginners guide â part 1
The idea for this posts arose from my frustration on not finding any organized documentation for learning FFmpeg. Thus, my aim in writing this series has been to provide newbie learners to quickly get up-and-running with FFmpeg.
FFmpeg is a command-line tool for *nix and Windows systems that, in its simplest form, provide a facility to decode and an encode media files. With the proliferation of video on the Internet and in our daily lives, users need the ability to transcode (convert) audio and video files from one format to another. For example, a user might have downloaded a video from YouTube and need to convent it to a format playable on an iPod or other media device.
Besides this obvious use, FFmpeg is also capable of a few other fundamental manipulations on the audio and video data. These manipulations include changing the sample rate of the audio and advancing or delaying it with respect to the video, reducing the size of the media file. They also include changing the frame rate of the resulting video, cropping it, resizing it, placing bars left and right and/or top and bottom in order to pad it when necessary, or changing the aspect ratio of the picture. Furthermore, ffmpeg allows importing audio and video from different sources such as a microphone.
The main components of FFmpeg are libavcodec, an audio/video codec library, libavformat, an audio/video container mux/demux library, and the ffmpeg command line program for passing various transcoding options to the main program.
The FFmpeg project was started by Fabrice Bellard, and has been maintained by Michael Niedermayer since 2004. The name of the project comes from the MPEG video standards group, together with “FF” for “fast forward”. On March 13, 2011 a group of FFmpeg developers decided to fork the project under the name Libav (http://libav.org/) due to some project management related issues.
FFmpeg is used by many open source and proprietary projects, including ffmpeg2theora, VLC, MPlayer, HandBrake, Blender, Google Chrome, and various others.
1.1.2 Components of FFmpegFFmpeg is made of the following main components.
Programs
ffmpeg – a command line tool to convert multimedia files between formats.
ffserver – a multimedia streaming server for live broadcasts.
ffplay – a simple media player based on SDL and the FFmpeg libraries.
ffprobe – a simple multimedia stream analyzer.
Libraries
libavutil – a library containing functions for simplifying programming, including random number generators, data structures, mathematics routines, core multimedia utilities, and much more.
libavcodec – a library containing decoders and encoders for audio/video codecs.
libavformat – a library containing demuxers and muxers for multimedia container formats.
libavdevice – a library containing input and output devices for grabbing from and rendering to many common multimedia input/output software frameworks, including Video4Linux, Video4Linux2, VfW, and ALSA.
libavfilter – a library containing media filters.
libswscale – a library performing highly optimized image scaling and color space/pixel format conversion operations.
In this posts we will primarily focus on the ffmpeg program, the other programs like ffserver are used for video broadcasts and is outside the scope of this posts. Among the libraries, the most notable parts of FFmpeg are libavcodec, an audio/video codec library, and libavformat, an audio/video container mux and demux library
1.1.3 CompressionTo be honest, trying to shoehorn the complete details of audio and video in a paragraph or two is plainly ridiculous, as the topic is rather complex. But since this is a beginnerâs guide, a few basic overviews will be enough to get you started using ffmpeg properly.
If you are working with audio and video, you are well aware that these files take an inordinate space for storage. You cannot easily work with these files if they were not compressed beforehand. Assuming an NTSC standard video format; a raw (uncompressed) video at 720×480 pixels, 30 frames per second and 24-bit RGB color, would take about 1,036,800 bytes (1 Mb) per frame. That’s almost 30MB per second, or over 200GB for a 2-hour movie. And that’s just the video. Audio stream also takes additional storage. Something needs to be done so that the movie can be stored on a consumer-grade medium such as a DVD. The data needs to be compressed beforehand.
Conventional, lossless compression algorithms such as ZIP, which everyone uses on a regular basis, don’t reduce the size of the data enough, so we need to look into lossy compression for further size reduction. Lossy compression works by discarding some data in the media which results in smaller file sizes. So now you might be thinking what data the compression algorithm discards. Well in general the algorithm does not discard any random data, which would be a disaster. The compression algorithm discards data only if it thinks that the data is redundant. For example in movie frames many times not much changes between successive frames; if the compression software discards some of these frames the viewer will hardly notice any difference, but the storage requirement of those frames have been saved.
Lossy compression is commonly used to compress multimedia data such as audio, video and still images. The only negative aspect of lossy compression is that as some data is removed during compression which can reduce the fidelity of the output.
The algorithms that allow us to encode and decode the data, whether by using lossy or lossless technique are called codecs. Several codecs are enclosed in the libavcodec library supplied with ffmpeg, which enables you to work with a wide variety of video and audio formats.
Once the audio and video streams have been encoded by their respective codecs, this encoded data needs to be put together into a single file. This file is called the âcontainerâ. A graphic of the process is shown below.
1.1.4 BitratesA movie is made-up of two main components, Audio and Video. Both “components” produce a separate stream of data that must be decoded by your DVD-player or some program so we can see and hear the video properly.
The bitrate of a movie is the key to the quality of the audio and video of that movie. Also, particular formats specify the bitrate or the maximum bitrate to be used. Bitrate is a measurement of the number of bits that are transmitted over a set length of time. Your overall bitrate is a combination of your video stream and audio stream in your file with the majority coming from your video stream. Bitrate denotes the average number of bits that one second of audio or video data will take up in your compressed bit stream. The overall bitrate of your movie is a combination of your video stream and audio stream in your file with the majority coming from your video stream.
A bit rate is usually measured in some multiple of bits per second – for example, kilobits, or thousands of bits per second (Kbps – for example, kilobits, or thousands of bits per second (Kbps).
Bitrates come in two versions – VBR (Variable Bit Rate encoding) or CBR (Constant Bit Rate encoding). VBR allows a higher bitrate (and therefore more storage space) to be allocated to the more complex segments of media files while less space is allocated to less complex segments. The average of these rates can be calculated to produce an average bitrate for the file. VBR allows you to set a maximum and minimum bitrate. The compression algorithm then tries to efficiently compress the data reducing to the minimum bitrate when there is little or no motion on screen and increasing to the maximum defined rate when the motion is prevalent. This helps to give you a smaller overall file size without compromising the quality of the video.
CBR is used when a predictable flat bit rate is needed. Although the flat bitrate throughout the entire file comes at the price of efficiency for the codec; usually resulting in a larger file, but smoother playback. CBR is useful for streaming multimedia content on limited capacity channels since it is the maximum bit rate that matters, not the average, so CBR would be used to take advantage of all of the capacity. CBR would not be the optimal choice for storage as it would not allocate enough data for complex sections (resulting in degraded quality) while wasting data on simple sections.
Depending on your video you might want to use a VBR for a streaming playback if the sudden spikes do not exceed your target user’s connection speed. For example if there is only one high motion scene in a video, you will be wasting considerable bandwidth on a CBR throughout the entire file and may better serve your user’s need by using a VBR. Either way try experimenting with the two settings to find what works best for your video.
Briefly, a bitrate specifies how many kilobits the file may use per second of audio. The following shows the quality for various standard audio bitrates.
64 Kbps Audio encoded at 64 Kbps have a 15:1 compression ratio. This bitrate is not recommended for digital music but is acceptable for voice-only recordings. 96 Kbps Audio encoded at 96 Kbps have a 15:1 compression ratio. One minute of music will be about 700KB of disk space. 128 Kbps Audio encoded at 128 Kbps have an 11:1 compression ratio. One minute of music is takes around 1MB of disk space. 160 Kbps Audio encoded at 160 Kbps have a 9:1 compression ratio. One minute of music will is about 1.5MB of disk space. 192 Kbps and above MP3s encoded at this setting take up the most space but have CD quality sound and can take up to 2MB of space per 60 seconds of music. Online music stores or music download services will have at least this high of a bitrate. 1.1.5 Audio Sampling FrequencyThe audio sampling frequency is the number of times per second audio is sampled and stored – CD audio is sampled at 44.1 KHz, which means when the sound is converted from analog to digital, 44100 samples per second are taken of the audio signal. The higher the sampling rate the audio has, the wider the frequency range it provides. In other words, higher is better quality. Your lows will be lower; your highs will be higher. For example the following image shows an analog signal on the left converted to a digital representation using two different sampling rates. As you can see the higher sampling will lead to an even more exact reproduction of the original signal.
The sample rate can be thought of as how often or how much the sound is described. CD quality audio has 44,100 of these measurements a second. Thatâs why itâs called 44.1 kilohertz (khz).
So what is the relationship between bitrate and sampling frequency? Bitrate simply specifies the number of bits per second that are used to encode the audio stream. The uncompressed bitrate for CD audio is 16 bits x 44100 samples x 2 channels = 1411200bps, or approximately 1411kbps. When audio is stored in an uncompressed format, the bitrate is a linear function of the sample rate; i.e. doubling the sample rate doubles the bitrate.
With uncompressed audio, there is a direct relationship between the sample rate and the bitrate. A 44.1kHz 16-bit stereo signal takes 1411.2 kbps, or approximately 10.4Mb per minute to record. A 44.1kHz 16-bit mono file would take half of this, as would a 44.1kHz 8-bit stereo file or a 22.05kHz 16-bit stereo file.
But now formats like Ogg Vorbis and MP3, compress audio by making calculated guesses about the sounds humans aren’t likely to hear and then discard these sound samples. As part of this process, such formats allow us to make some of the decisions by deciding how much to throw away, or to put it more simply, how much data to use to represent the original sound. So, using our 44.1kHz stereo sample, we can choose to use as little as 48kbps or as much as approx 500kbps to store this sound. At 500kbps, more of the original sound fidelity is preserved than at 48kbps.
Calculating values
An audio file’s bit rate can be easily calculated when given sufficient information.
Bit rate = (sampling rate) x (bit depth) x (number of channels)
e.g., a recording with a 44.1 kHz sampling rate, a 16 bit depth, and 2 channels:
44100 x 16 x 2 = 1411200 bits per second, or 1411.2 kbit/s
The file size of an audio recording can also be calculated using a similar formula:
File Size (Bytes) = (sampling rate) x (bit depth) x (total channels) x (seconds) / 8
e.g. a 70 minutes long CD quality recording will take up 740MB:
44100 x 16 x 2 x 4200 / 8 = 740880000 Bytes
Some standard sampling frequencies with their applications is given below.
Sampling Rate Use 8,000 Hz Telephone, walkie-talkie, wireless intercom and wireless microphone transmission; adequate for human speech. 11,025 Hz used for lower-quality PCM, MPEG 22,050 Hz One half the sampling rate of audio CDs; used for lower-quality PCM and MPEG 32,000 Hz miniDV digital video camcorder, video tapes with extra channels of, DAT, High-quality digital wireless microphones, digitizing FM radio. 44,100 Hz Audio CD, also most commonly used with MPEG-1 audio (VCD, SVCD, MP3). Most professional audio equipment uses 44.1 kHz sampling and above. 48,000 Hz he standard audio sampling rate used by professional digital video equipment such as tape recorders, video servers, vision mixers and so on. Also used for sound with consumer video formats like DV, digital TV, DVD, and films. 96,000 Hz DVD-Audio, some LPCM DVD tracks, Blu-ray Disc audio tracks, HD DVD High-Definition DVD) audio tracks. 1.1.6 Frame rateThe frame rate is how many unique consecutive images are displayed per second in the video to give the illusion of movement; each image thus is called a âframeâ. The human brain perceives a smooth continuous motion if shown around 24 frames per second. If the frames are less than this magic number, you will see a jerky motion rather than a smooth one. Most video creators use this frame rate.
This is not a standard of course, if your video is a screen cast you can get to frame rates as low as 5fps. Television standards such as PAL (common in Europe and some parts of Asia) uses 25fps, while NTSC standard (used in the US and Japan) uses 29.97fps. Generally you should never exceed the frame rate of the source video. Obviously, the best results will be achieved if the frame rate is kept the same as your original source.
1.1.7 ContainersA container file is used to identify and combine different data types. Simpler container formats can contain different types of audio formats, while more advanced container formats can support multiple audio and video streams, subtitles and meta-data â along with the synchronization information needed to play back the various streams together. In most cases, the file header and most of the metadata are specified by the container format. For example, container formats exist for optimized, low-quality, internet video streaming which differs from high-quality DVD streaming requirements.
The video file formats weâre familiar with, such as Quicktime movies (.mov), .avi are media container formats. Some container formats just contain audio, like WAV file fro Windows, MP3 music files or AIFF files for Macs. Others contain audio and video, such as ASF files for Windows, which contain audio compressed with the WAV codec and video compressed with the WMV codec. There are dozens of these container formats. If youâre uploading a video to an online site, check to see what formats the site supports. Sometimes this can be confusing because the list of accepted formats may have both compression formats like MPEG-4 and container formats like .mov listed.
1.2 Installing FFmpegFFmpeg is developed under GNU/Linux, but it can be compiled under most operating systems, including Mac OS X, Microsoft Windows, AmigaOS. In most of the Linux distros, you can directly install ffmpeg using their respective package managers. But in case you are looking for installing the latest version or want to customize the installation, you might need direct installation from the source code too, but as it is an involved and tricky procedure, Iâm not discussing it here.
Installing FFmpeg on Ubuntu
Run the following command in the terminal to install FFmpeg.
$ sudo apt-get install ffmpeg
Installing FFmpeg on Fedora
FFmpeg can be directly installed from the repos using the following command.
$ su -c 'yum install ffmpeg'
Installing FFmpeg on CentOS
FFmpeg can be directly installed from the repos using the following command.
$ yum install ffmpeg ffmpeg-devel
Installing FFmpeg on Windows
By far the easiest way to start using FFmpeg is to get a precompiled binary. Zeranoe.com has pre-built binaries for windows, which makes it easier to install ffmpeg. So if you are using Windows you can get up and running FFmpeg in no time. Go ahead and grab the binaries from the below link.
http://ffmpeg.zeranoe.com/builds/
Once installed use the following command to get the ffmpeg version and the versions of the codecs installed.
C:\ffmpeg>ffmpeg -version
On my Windows machine it returns the following; of course this may be different on your system, depending on the version of FFmpeg installed:
ffmpeg version N-31100-g9251942, Copyright (c) 2000-2011 the FFmpeg developers
built on Jun 30 2011 21:17:59 with gcc 4.5.3
libavutil 51. 11. 0 / 51. 11. 0
libavcodec 53. 7. 0 / 53. 7. 0
libavformat 53. 4. 0 / 53. 4. 0
libavdevice 53. 2. 0 / 53. 2. 0
libavfilter 2. 24. 0 / 2. 24. 0
libswscale 2. 0. 0 / 2. 0. 0
libpostproc 51. 2. 0 / 51. 2. 0
ffmpeg N-31100-g9251942
libavutil 51. 11. 0 / 51. 11. 0
libavcodec 53. 7. 0 / 53. 7. 0
libavformat 53. 4. 0 / 53. 4. 0
libavdevice 53. 2. 0 / 53. 2. 0
libavfilter 2. 24. 0 / 2. 24. 0
libswscale 2. 0. 0 / 2. 0. 0
libpostproc 51. 2. 0 / 51. 2. 0
Adhering to the UNIX culture, FFmpeg relies on a plethora of command-line options to do its work. The generic syntax of an FFmpeg command is shown below.
ffmpeg [[infile options]['-i' infile]]...{[outfile options] outfile}...
Each section of the command is explained below.
ffmpeg – The first is the FFmpeg executable file name.
infile option – This is where you put options for your input video or audio file. This tells FFmpeg to apply any options give here to the input file before processing starts. This section is not as widely used as the âoutfile optionsâ.
-i infile – This is the actual video or audio file you use for processing, and also the directory of where it is located.
e.g /home/george/media/myvideo.flv. You will always need to include the `-i` option before your file name.
outfile options – This is where you will put the various options that are required which you want to be applied to the video or audio you will be creating.
outfile â The name of the output file you want to create, and also the directory path if it not the same as your input file directory.
e.g is /home/george/media/out.flv
Now that we have FFmpeg installed, in the next post we will learn about audio processing.
Subscribe now to get the next post update.
Server-Side Magazine: 10 Questions with Facebook Research Engineer - Andrei Alexandrescu
The Server-Side Magazine site has posted an interview (10 questions) with Andrei Alexandrescu, a research engineer currently working at Facebook.
Today we caught up with Andrei Alexandrescu for a "10 Question" interview. He is a Romanian born research engineer at Facebook living in the US, you can contact him on his website erdani.com or @incomputable. We will talk about some of the juicy stuff that going on at Facebook, so let's get started.Their questions include:
- What's your development setup?
- What do you think of PHP as a language from your perspective, regarding that Facebook was initially written in PHP then transformed to C++ using HipHop for PHP. What are the pros and cons of using C++ over PHP at Facebook?
- Currently, what kind of research do you conduct at Facebook? (or is this confidential?)
- Tell us a little bit about the D programming language, in contrast to C, PHP, Ruby and others. In what fields can someone apply D?
- Also, what kind of advice can you give for developers who are considering to apply to Facebook? What kind of skills is Facebook looking for in a potential candidate. Is it really important to be a graduate CS? What kind of skills do the majority of Facebook employees possess?
Read the full interview for his answers to these and other interesting questions.
Rafael Dohms' Blog: PHP Benelux 2012 - Learning lessons
Rafael Dohms has a new post to his blog about some of the lessons he learned attending this year's PHP Benelux conference both from the perspective of attending the conference and having been at several conferences around the world.
After hearing about how great PHP Benelux Conferences were I finally made it over to Belgium to check it out, and i was impressed. To catch you up on the new, I moved to Amsterdam last december and thus had the chance of attending the conference which is now 2 hours away on a train ride. I could not expect less of a wonderful conference when names like Michelangelo van Dam are involved and this was no exception.Among his suggestions, there's things like:
- Value your sponsors
- Value your attendees
- Make your attendees pay
- Value the organizers and your volunteers
...and one of the most important ones: "Have Fun!" If you're not following this piece of advice, you're probably doing it wrong.
Community News: php|tek 2012 Schedule Announced!
php|architect, the group behind the yearly php|tek conference has posted this year's official schedule. Sessions in this year's event include:
- Developer Testing 201, When to Mock and When to Integrate (Laura Beth Denker)
- API Development (Rob Richards)
- The MicroPHP Manifesto (Ed Finkler)
- Web Security and You (Elliot White)
- Decoupled Library Packages for PHP 5.4
- Clojure for PHP Developers (Ian Barber)
Tickets are now on sale - you can find out more on the sales page for the event.
PHPClasses.org: Lately in PHP podcast episode 20 - MicroPHP vs Complicated PHP
The PHPClasses.org site has posted the latest episode of their "Lately in PHP" podcast - episode 20: "MicroPHP vs Complicated PHP".
Earlier in January Ed Finkler announced the MicroPHP manifesto. It seems to be a rant about against the practices of developers that make PHP development more complicated than it should be. This is one of the main topics discussed by Manuel Lemos and Ernani Joppert in the episode 20 of the Lately in PHP podcast. They also discuss the final release of PHP 5.4.0 and whether you should upgrade it or not, the repercussion of the PHP Hash Collision Vulnerability, as well the trends of PHP world based on the analysis of the PHP Zeitgeist 2011 initiative.You can listen to this latest episode either by using the in-page player or by downloading the mp3.
Sebastian Bergmann's Blog: A Tool's Tale
Sebastian Bergmann has shared a presentation he originally gave at an Etsy event covering some of the history behind the popular PHPUnit tool and the development it's been through.
When Noah Sussman asked me to give a Code as Craft Technology Talk last week when I was consulting for Etsy I immediately said yes. [...] Just like with a talk that I gave last year, I suddenly had a chain of associations in my head that I just had to follow. And down the rabbit hole I went once more ...He talks about the origins of PHPUnit (and mentions a few other tools), the move from PHP4 to PHP5, a change in version control from SVN to Git and features of the tool including mock objects and data providers. He also notes that not all tests are "good tests" and how, sometimes, backwards compatibility breaks are a good thing.
Lorna Mitchell's Blog: Building A RESTful PHP Server: Output Handlers
Lorna Mitchell is back with another post in her "Building a RESTful PHP Server" series today with this new post showing how to work with output handlers (her focus is on JSON).
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.She advocates using output handlers instead of the usual views you'd think of in a typical MVCish sort of application. The difference here is that there's not a lot of extra overhead to produce the results - it's literally an output directly from a class extending the base view (including the correct headers). She also briefly mentions the inclusion of JSONP functionality, allowing you to specify a local callback to execute when the request is returned. A few other "nice to haves" are also mentioned like the number of results returned and pagination support.
Practical PHP Refactoring: Replace Delegation with Inheritance
A Tool's Tale
When Noah Sussman asked me to give a Code as Craft Technology Talk last week when I was consulting for Etsy I immediately said yes. However, I was a bit surprised when the talk was announced under the title "An Evening with Sebastian Bergmann". When I read that title the first time, it was just minutes after Arne, Stefan and I had talked about one of our favourite scenes from "A Knight's Tale":
Chaucer: I'm a writer.
Wat: A what?
Chaucer: A wha- a what? A writer. You know, I write, with ink, and parchment. Geoffrey Chaucer's the name, writing's the game. You've probably read my book? The Book of the Duchess? No? Well, it was allegorical.
Roland: Well, we won't hold that against you, that's for every man to decide for himself.
Just like with a talk that I gave last year, I suddenly had a chain of associations in my head that I just had to follow. And down the rabbit hole I went once more ...
Hi! I have no idea why this talk is titled "An Evening with Sebastian Bergmann". I hope that this evening will turn into an interesting discussion about PHPUnit and all things testing. To break the ice, and to not appear completely unprepared, I came up with the following slides ...
So I recently talked with my friends Arne and Stefan about the movie "A Knight's Tale". Somehow the idea stuck in my head that a variation of that title might be a good idea for a talk of mine. After dismissing "A Fool's Tale" I arrived at "A Tool's Tale". So that's what we're stuck with and what I am going to try right now ...
What I just did was a variation on how Geoffrey Chaucer introduces himself in the movie.
Some time in 2001 I started to work on PHPUnit because I wanted to have something like JUnit for PHP. The initial "port" was completed within one weekend. The code was ugly because I had to emulate exception which PHP 4 did not have. On November 27th 2001 I checked the code into cvs.php.net.
A lot has changed since 2001. Hopefully not very many developers are still stuck with PHP 4. As of PHPUnit 2.0, which was released on July 14 2004, the day after PHP 5.0.0 was released, PHP 5 is required to run PHPUnit.
PHPUnit is neither the only testing framework nor the only quality assurance tool for PHP. Over the last years a nice ecosystem of static analysis tools started to grow.
I get this question a lot: why do only Germans work on tools that tell me that my code is bad? I do not have an answer for this, sorry. But the statement is also not true: PHP_CodeSniffer is not developed by a German.
PHP has changed and so the have the tools we use to write and maintain code. In 2006 the PHPUnit code was migrated from CVS to Subversion ...
... and in December 2009 from Subversion to Git and GitHub.
PHPUnit is no longer one big monolithic package. It has been refactored to components that are being reused by other testing frameworks, for instance. Unfortunately, this refactoring was not without problems.
PHPUnit gets more and more convenience functionality. Here are a couple of examples:
Tests can be written, both unintentionally and intentionally, in bad ways. Bad tests can lie. They can give you a false sense of security by reporting that something is tested when it really is not.
This is why I started iplementing coutermeasures against bad tests such as the (ultimately useless but still interesting) assertion counting ...
... as well as the strict execution mode.
There is code in PHPUnit that I am not proud of. I am trying to make the world a better place by eliminating one singleton at a time, for instance. Unfortunately, cleaning up code sometimes breaks things. Contrary to what a popular opinion on Twitter is, I do not like breaking backwards compatibility in PHPUnit and try really hard to avoid it.
This is a "good" example of such a backwards compatibility breakage. It happened in PHPUnit 3.6 because I eliminated a Singleton. Had I known that many developers used this API (instead of the XML configuration file) to set up a code coverage blacklist or whitelist I would probably not have done the change. If more people would have tested the release candidates leading up to PHPUnit 3.6 they could have told me ... oh well.
At this point the "Evening with Sebastian Bergmann" turned into the interesting discussion I had hoped for.
Alessandro Nadalin's Blog: Managing PHP dependencies with composer
Alessandro Nadalin has a new post to his blog looking at the Composer project and using it to manage packages and dependencies in PHP applications.
Managing dependencies between pieces of software, in PHP, hasn't always been a relief: we had PEAR and PECL with their workflows and problems while, in other ecosystems, the solution to this problem has been solved in better ways, like NodeJS's NPM.He takes a first look at the tool, describing how to get it set up, create a sample configuration (describing each section inside it) and an example of the tool's output. He also briefly touches on the Packagist website/repository and links to the instructions on how to create your own.
Justin Carmony's Blog: SMS Nagios Notifications with PHP & Twilio
In this latest post to his blog Justin Carmony looks at a system he created to hook his Nagios notifications into the Twilio web service and have it notify him via SMS with something was wrong.
In the past I would just use my iPhone's email-to-txt email address. However, when I received the txt message, it wasn't formated very pretty, and it would have a different "From Number." So if we had a crazy day, I would have 20-30 message threads in my iPhone all about Nagios. [...] What I like out this setup is with Twilio, I can buy a phone number for $1 a month. So all my notifications come through the same number.He's included the PHP code he uses to send the notifications (using the Twillo library) and the Nagios commands he configured to send the notifications to that script via the command line.


