![]() |
Planet PHPAn intriguing use of lambda functions - Eli WhiteI’ve been working hard on Goodsie.com lately trying to bring it to launch. It’s been great being in on a new PHP project from (near) the beginning, as it frees up a number of things. One of those, is the fact that I can be using PHP 5.3 and all the new features that come with PHP 5.3. While I’ve used my fair share of the short-cut ternary already (?:), the bigger win for me, are the Lambda functions with scoping (anonymous functions). I found a very specific use out of the blue of Lambda functions that I have now used and I see as a great use-case. Which is specifically passing functions/logic from your Controller to your View. In the case of Goodsie, I’m using PHP for my templating language and as usual I’m trying to remove as much logic from my View as possible, while still allowing the view to be malleable. The specific case I had, was a subview that was generating some pagination code for me. You know, the standard ‘previous, page 1, page 1, next’ section of links. The basic html template I had, looked looked similar to: <div class="pagination"> <a href="<?= $baseurl . '/page:' . ($page - 1) ?>">← Previous</a> Page <?= $page ?> of <?= $total ?> <a href="<?= $baseurl . '/page:' . ($page + 1) ?>">Next →</a> </div>Rather straight forward, but I quickly ran into a problem. The way it worked, as you see, is that you passed in a base URL, and the page number you are currently on, and it generated appropriate forward/back links. (Ok, there was also some other logic where it determined if you needed the prev/next links at all, but I’ve removed that for clarity) But I then had a case, where I wanted to reuse this subview in an ajax situation. Where instead of straight URL’s being passed in, I might want to pass in a javascript function, and have that function be called with the page number as a parameter. That would be nice as I could use it in both situations. What pagination looked like, could completely change, and still work on both cases. Perhaps we’d want to give a full list of all possible pages. Or show a couple forward/back, etc. The view could handle all of that without a change to the controller. But therein lied the problem. When using a URL based pagination, I wanted to concat the page number onto the end of the URL. But when using javascript, it wasn’t pure concatenation, it instead needed to wrap the page number with the function call. Oh the pain a simple ) could cause me. I started writing code, where I ended up with tons of switch statements and logic inside of the view. I’d have to pass in two different possible values, a URL or a javascript function. The view at every point where it would output a link, would need to see which version was being used, and from that decide what type of output to create. In short, it was a mess. But then the solution dawned upon me. A lambda function would work admirably here. So what I did, is inside of my controller I created a function on the fly, that would generate the appropriate type of link that I was wanting. It looks something like: if ($jsfunc) { $url = function ($p) use ($jsfunc) { return "javascript:{$jsfunc}({$p})"; }; } elseif ($baseurl) { $url = function ($p) use ($baseurl) { return "{$baseurl}/page:{$p}"; }; }Now I could simply rewrite my original template, to use this lambda function $url to generate it’s URLs. <div class="pagination"> <a href="<?= $url($page - 1) ?>">← Previous</a> Page <?= $page ?> of <?= $total ?> <a href="<?= $url($page - 1) ?>">Next →</a> </div>Now not only would this work for my specific situation, but ANY controller could reuse this pagination subview and define exactly how it wanted it’s URLs to be formed. Now, the view could completely change around how the pagination section is displayed, show as many, or as few pages as it wants to, and all that without ever touching the controller. This is one simple example, but I’ve become enamored of this approach. Using lambda functions in this way, you are able to have complicated logic represented inside of your view, but encapsulated/created by the controller. Also of note is the fact that the view is managing to use the $jsfunc and $baseurl values, but without actually having to be granted access to them. This allows for another level of encapsulation, as I exposed one function, Truncated by Planet PHP, read more at the original (another 1389 bytes)
Categories: PHP
Accelerando - Tobias Schlitt
This is a very unusual blog post for the open source area of my website, since it contains a recommendation for a science fiction book. The reason I've put it here instead of the private section is on the one hand, that it will definitely reach more geek - and therefor probably scifi interested - people here. On the other hand, the book I'm writing about can be found online for free in English language, but the private section is mostly kept in German.I love scifi literature and movies, as most geeks do. But the quality of works in this area varies quite a lot. Beside the style of writing, there is one crucial point, which can make the best novel be a total disaster: Authenticity.
Categories: PHP
First year of Qaiku, and a travel writing challenge - Henri BergiusQaiku, the conversational microblogging service that launched a year ago had a refresh that launched today. While it hasn't yet convinced the twittering masses, it has already proven itself as a lot more thoughtful platform for the Finnish online community, and as a valuable workstreaming tool. The new version looks quite nice and fresh. Notice the privacy information on the right-hand side, which is relevant as Qaiku allows channels and profiles that are private or invitation-only: Technically the new version is also remarkable as it is the first major website to run fully on top of the legacy-free Midgard2 platform. So yes, every entry you see there is a GObject. And D-Bus signals fly when you post. On to the challenge, thenTo highlight Qaiku's threading, conversational nature I started a new "On my travels, I have" thread for sharing your most extraordinary travel experiences. This is not on Twitter or Buzz as with Qaiku it is so easy to keep the conversation together and accessible for the future as well. To contribute, sign up on Qaiku, go to the thread and add your experiences as a comment. If you have a link or picture to include, you can also do so. My first entry was: seen ice descend from the heavens and provide us with cold beer on a hot day in LesothoWill be interesting to see what comes out of this :-)
Categories: PHP
Getting started with the Midgard content repository - Henri BergiusI'm doing a talk today in the Bossa Conference about using Midgard as a content repository for mobile applications. As part of my presentation I wrote some simple example code for using the Midgard APIs in Python, and thought they would be good to share to those not attending the event as well. The idea of a content repository is that instead of coming up with new, isolated file formats or database setups for your application you can just work with objects and signals, and let Midgard handle the rest. This is something that lots of people are doing with CouchDB as well, but we feel Midgard, with its light footprint and native APIs for languages like Python, C, Vala and PHP fits better in the mobile applications context. Installing MidgardMidgard packages are available for many different Linux distributions through the OpenSuse Build Service. To find the right repository for your setup, go to the OBS project page. For example, on my Ubuntu Karmic netbook the URL to add to apt sources.list is deb http://download.opensuse.org/repositories/home:/midgardproject:/mjolnir/xUbuntu_9.10/ ./. Then I just: sudo apt-get update sudo apt-get install python-midgard2Midgard is also available in Maemo extras and for OS X on MacPorts. Defining a schemaThe first thing when developing a Midgard application is to define your storage objects. This is done using the MgdSchema XML format. In this case we're doing a simple "attendee" object that amends Midgard's built-in person record with information related to the conference: <?xml version="1.0" encoding="UTF-8"?> <Schema xmlns="http://www.midgard-project.org/repligard/1.4"> <type name="openbossa_attendee" table="openbossa_attendee"> <property name="id" type="unsigned integer" primaryfield="id"> <description>Local non-replication-safe database identifier</description> </property> <property name="person" type="unsigned integer" link="midgard_person:id"> <description>Person attending the event</description> </property> <property name="registration" type="datetime"> <description>Registration date of the attendee</description> </property> <property name="likesbeer" type="boolean"> <description>Whether the attendee likes beer</description> </property> </type> </Schema>Then we just save this XML file into /usr/share/midgard2/schema/ so that Midgard will find it. Initiating the repository connectionOnce the MgdSchema is in place it is time to import antigravity and start hacking in Python. The code works pretty much in the same way in other languages Midgard is available for, but Python is used here for the sake of simplicity. First we load the Midgard extension: import _midgard as midgardThen we setup the repository connection. With these settings we will store our content into an SQLite database located in ~/.midgard2/data/midgardexample.db: configuration = midgard.config() configuration.dbtype = 'SQLite' configuration.database = 'midgardexample' # Open a Midgard repository connection with our config connection = midgard.connection() connection.open_config(configuration)As this is the first time we're interacting with the repository we need to tell Midgard to prepare the storage for itself and also for our new openbossa_attendee class: midgard.storage.create_base_storage() midgard.storage.create_class_storage('midgard_person') midgard.storage.create_class_storage('midgard_parameter') midgard.storage.create_class_sTruncated by Planet PHP, read more at the original (another 2314 bytes)
Categories: PHP
Neural Networks in PHP - PHP Classes
Neural Networks in PHP
By Louis Stowasser
Neural networks allow emulating the behavior of a brain in software applications. Neural Networks have always had a too steep learning curve to venture towards, especially in a Web environment.
Neural Mesh is an open source, pure PHP code based Neural Network manager and framework that makes it easier to work with Neural Networks. This article explains how to easily implement Neural Mesh to develop Neural Network applications in PHP.
Categories: PHP
CMS Watch on their Midgard usage - Henri BergiusWhich CMS does The Real Story Group Use? (Tony Byrne / CMS Watch): The answer is, we use an open-source platform called "Midgard." We picked it nearly ten years ago, and it has held up fairly well.... One of the things we like about Midgard actually makes it rather unsuitable for many simpler publishing scenarios: it is highly object-oriented. This allows us to run multiple sites off largely a single codebase -- at the cost of quite user-unfriendly administrative and authoring facilities. Also, Midgard is very much a development platform, and we have had to create a fair amount of custom code, especially to handle structured content. In that regard, our CMS experience probably resemble yours. As an industry we remain very far from plug-and-play content management technology for all but the simplest of websites. While the post contains many negative points about older Midgard (the UIs are a bit better now than they used to be, quite a lot of development has since been happening especially in the LTS branch), it is remarkable that CMS Watch has been able to run their services through the same CMS setup for ten years. This really shows the durability and commitment to long-term stability we have in the Midgard community. We've been doing this for more than ten years, and will likely keep going for quite a bit longer. As for usability and popularity of Midgard, there is quite little we can do about it in the Midgard1 area, as that is now in long-term support phase that won't allow major changes. But Midgard2 is a new world with new opportunities. Midgard's content repository is pretty much there already, as is the MVC layer, and this spring we should be able to unveil the new, quite revolutionary CMS concept as well. Watch this blog for updates!
Categories: PHP
Upgrades In Open Source - Brandon Savage
PHP 5.3 has been out now for eight months, and in that time lots of projects have made decisions to begin developing against this version of PHP. Juozas Kaziukenas makes the argument that you shouldn’t be afraid of PHP 5.3 and he provides a number of excellent points to support his argument.
I don’t dispute [...]
Categories: PHP
Seed doc updates, and Gio async directory listing - Alan Knowles
The documentation for seed gobject introspection is improving continually, I now have a jhbuild virtual machine, which is picking up the latest versions from git.
In addition many of the documentation details have been expanded, including
However within 5 minutes with the documentation, I was able to write a small script to do this.Gio = imports.gi.Gio; Gtk = imports.gi.Gtk; var f = Gio.file_new_for_path('/home/'); f.enumerate_children_async ( "*", Gio.FileQueryInfoFlags.NONE, GLib.PRIORITY_DEFAULT, null, function(o,ar) { // listing completed.. var fe = f.enumerate_children_finish(ar); var ch = false; while (ch = fe.next_file(null)) { Seed.print(ch.get_name()); } Seed.quit(); }, null); Gtk.main();
Categories: PHP
My NAS - QNAP TS 119 Turbo NAS - Andrey HristovFew weeks ago I got new hardware for my home network, a QNAP TS 119 Turbo NAS.
Categories: PHP
PHP London Conference: In Review - Lorna Mitchell
I'm really late with this post, but I wanted to write about the PHP London Conference which was held in London last Friday. The event was in a great venue and had hoards of people - this was my fourth year in attendance!! They do, however, have the longest twitter tag in history #phpuk2010!
This year I had the privilege of speaking at this event, although I was concerned that I had to stay coherent and alert right through to the graveyard slot at 4:30pm (conference organisers take note: I really am much sparklier in the mornings!). I kept myself awake by attending what I affectionately refer to as the "Ibuildings track" - with 4 speakers at the event, it did feel like a bit of an invasion by myself and my colleagues. In our defence I can only say that we are a pretty big local PHP employer and, as a developer, I'm happy to be working for someone who sends all their developers to these events, and even happier to be in the company of those other excellent speakers as colleagues! My talk was entitled "Best Practices in Web Service Design" although perhaps "Things I Wish Web Service Creators Would Consider Before Writing Unclear and Unstable Useless And Frustrating Services" would have been a better title! I talked about web services in general, a bit about HTTP and the various service types, and also gave some general tips and tricks for writing good, stable services. In a bit of a break with geeky tradition, I then talked about services as a whole package, and how to deliver and document them in a way that helps users help themselves. If you are interested the slides are here: http://www.slideshare.net/lornajane/best-practices-in-web-service-design The experience was overall very positive for me, I haven't spoken at this conference before and I was very pleased to be included. My talk went quite smoothly, with my nerves nicely hidden away (I've had issues with this lately), and I also avoided falling over either the curtain or the piece of screen that was carefully placed to trip unwary speakers! I'd like to thank everyone who came and asked questions afterwards, and all those who saw my talk and left comments for me on my joind.in talk page - it all helps me to do better next time, thanks and I'll see you all next year!
Categories: PHP
Do you queue? Introduction to the Zend Server Job Queue - Zend Developer Zone
There has been a lot of talk over the past several years about the difference between performance and scalability. Never mind that the difference between the two will probably not really affect most developers. Never mind that the “difference between performance and scalability” argument is often used when someone’s code performs poorly and their best argument is “Yeah, but my code scales”. Yeah, sure it does.
Categories: PHP
Creating Scalable Vector Graphs with PHP - Zend Developer Zone
The Scalable Vector Graphics (SVG) specification provides a way to programmatically generate images using vector paths expressed in XML. This makes it ideal for generating images that need to be scaled to different resolutions without losing fidelity.
A common requirement in Web applications is to dynamically generate charts and graphs from numerical data. If these graphs are expressed using SVG, they can be blown up to different sizes without any deterioration in quality, and they are also typically smaller in size as compared to their GIF or JPEG counterparts. With this in mind, this article examines various open source PHP libraries that allow you to add SVG charting capabilities to your PHP application.
Categories: PHP
Suhosin-Patch 0.9.9.1 - Stefan EsserTogether with the release of PHP 5.3.2 by the PHP team I have released Suhosin-Patch 0.9.9.1 which comes with bugfixes and new features. The changes are:
Categories: PHP
Month of PHP Security - Blog Post Drawing - Stefan EsserWhile going through the HTTP_REFERER log of the Month of PHP Security website I realised that there are more incoming refers from various blog posts about it than there are submissions to drawing@php-security.org. Like I previously announced we will honor 10 blog postings with 25 EUR amazon coupons. The winners will be selected by random, however only among those we will select that announce their blogpost to us via the email address provided above. The reasons for this rule is very simple. Without the announcement we would have to look at every new HTTP_REFERER and manually check if it is just spam, an old link to the Month of PHP Bugs, someone who just copied the blog of another person or other nonsense. In addition to that we have to find a contact address of the person who originally has written the entry and ask him/her if he/she wants to take part in the drawing. This would be too much work. Therefore announce your blog posting to drawing@php-security.org or you have no chance of winning one of the coupons.
Categories: PHP
Performance improvement in Joomla with WINCACHE user cache to cache session - Venkat Raman DonNow that we have WINCACHE 1.1 Beta release which supports user as well as session cache, I am going to tell you a way to integrate session cache with Joomla using WINCACHE. Joomla has the way of integrating session cache based on user cache implementation and that’s what I am going to explain today. Increasing performance of Joomla by enabling it’s user cache functionality using WINCACHE is explained here. Joomla session code is modular enough and in order to enable session cache based on WINCACHE user cache, one needs to paste the below code in a file named wincache.php and place it at folder libraries joomla\session\storage. This folder path is relative to your Joomla root installation folder. <?php// Check to ensure this file is within the rest of the frameworkdefined('JPATH_BASE') or die(); /*** WINCACHE session storage handler for PHP** @package Joomla.Framework* @subpackage Session* @since 1.5* @see http://www.php.net/manual/en/function.session-set-save-handler.php*/class JSessionStorageWincache extends JSessionStorage{ /** * Constructor * * @access protected * @param array $options optional parameters */ function __construct( $options = array() ) { if (!$this->test()) { return JError::raiseError(404, "The wincache extension is not available"); } parent::__construct($options); } /** * Open the SessionHandler backend. * * @access public * @param string $save_path The path to the session object. * @param string $session_name The name of the session. * @return boolean True on success, false otherwise. */ function open($save_path, $session_name) { return true; } /** * Close the SessionHandler backend. * * @access public * @return boolean True on success, false otherwise. */ function close() { return true; } /** * Read the data for a particular session identifier from the * SessionHandler backend. * * @access public * @param string $id The session identifier. * @return string The session data. */ function read($id) { $sess_id = 'sess_Truncated by Planet PHP, read more at the original (another 7501 bytes)
Categories: PHP
How to avoid Identity Theft in Zend Framework with Zend Auth - Zend Developer Zone
While there are many major security issues possible in a web application, there is a particular one that bugged me for some time. The Identity theft - Broken account and session management issue.
Why can one so easily still my session id cookie and suddenly gain access to my account in one particular web application? I know it its rather impossible to make this 100% hack-proof but I strongly believe that the system should be improved as much as possible.
Our goal is to implement a Zend Auth extension that adds a new level of security to the previously mentioned class.
This extension - let's call it Project_Application_Auth - would check the Zend Auth storage for the IP and/or User Agent.
In order to do so, these should be set in the login process in the storage.
If the IP is different then the initial IP from the login process and / or the User Agent is not the same as the initial User Agent from the login process, then our extension would tell us that it is not a secure identity (aka it is safe to assume it has been stolen) and thus we should disconnect the user.
Categories: PHP
Performance improvement in Joomla using WINCACHE user cache - Venkat Raman DonNow that we have WINCACHE 1.1 Beta released which has got implementation for both user and session cache, one can easily take advantage of WINCACHE user cache and increase performance of Joomla. In this post I am going to tell you steps to use WINCACHE user cache with Joomla. Joomla caching code is modular and in order to enable WINCACHE user cache, one needs to paste the below code in a file named wincache.php and place it at folder libraries\joomla\cache\storage. All the folders mentioned here is with respect to root folder of Joomla installation. <?php// Check to ensure this file is within the rest of the frameworkdefined('JPATH_BASE') or die(); /** * WINCACHE cache storage handler */class JCacheStorageWincache extends JCacheStorage{ /** * Constructor * * @access protected * @param array $options optional parameters */ function __construct( $options = array() ) { parent::__construct($options); $config = & JFactory::getConfig(); $this->_hash = $config->getValue('config.secret'); } /** * Get cached data from WINCACHE by id and group * * @access public * @param string $id The cache data id * @param string $group The cache data group * @param boolean $checkTime True to verify cache time expiration threshold * @return mixed Boolean false on failure or a cached data string * @since 1.5 */ function get($id, $group, $checkTime) { $cache_id = $this->_getCacheId($id, $group); $this->_setExpire($cache_id); return wincache_ucache_get($cache_id); } /** * Store the data to WINCACHE by id and group * * @access public * @param string $id The cache data id * @param string $group The cache data group * @param string $data The data to store in cache * @return boolean True on success, false otherwise * @since 1.5 */ function store($id, $group, $data) { $cache_id = $this->_getCacheId($id, $group); wincache_ucache_set($cache_id.'_expire', time()); return wincache_ucache_set($cache_id, $data, $this->_lifetime); } /** * Remove a cached data entry by id and group * * @access public * @param string $id The cache data id * @param string $group The cache data group * @return boolean True on success, false otherTruncated by Planet PHP, read more at the original (another 10114 bytes)
Categories: PHP
Searching for a decent set of cans… - Mark DennehyThe old and fairly reliable Sennheiser RS40’s I was using up until a few weeks ago finally gave up the ghost in the run-up to Mobile World Congress this year – or to be more accurate, the battery packs finally…
Categories: PHP
Responding to Different Content Types in RESTful ZF Apps - Matthew Weier O'PhinneyIn previous articles, I've explored building service endpoints and RESTful services with Zend Framework. With RPC-style services, you get to cheat: the protocol dictates the content type (XML-RPC uses XML, JSON-RPC uses JSON, SOAP uses XML, etc.). With REST, however, you have to make choices: what serialization format will you support? Why not support multiple formats? There's no reason you can't re-use your RESTful web service to support multiple formats. Zend Framework and PHP have plenty of tools to assist you in responding to different format requests, so don't limit yourself. With a small amount of work, you can make your controllers format agnostic, and ensure that you respond appropriately to different requests. Continue reading "Responding to Different Content Types in RESTful ZF Apps"
Categories: PHP
A little light reading… - Mark DennehyWhat do you do when you’ve successfully gotten a demo to Mobile World Congress and you want to reward yourself? Go order a little light reading of course! Amazon are really getting to…
Categories: PHP
|
Recent blog posts
User loginPlanet PHP |
Recent comments
1 year 38 weeks ago