CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

Mariano Iglesias - Internationalizatio...

Why internationalize? You can attract a larger market by making content available in additional languages. When offering international content, you need to translate both the fixed and dynamic content in the database. In CakePHP you can facilitate translation with __() and __n(). In addition content stored in the database can be translated with TranslateBehavior. Multibyte characters exist in many languages, characters outside the traditional latin character set are represented with multibyte characters. This allows for the creation of additional characters and idiomatic expresssion. There is a PHP extentsion for using multibyte strings, it provides the mb_ functions. CakePHP also provides a MultiByte class which provides all the mb_ functions for PHP4 or PHP5 installations lacking them.

Using translation in CakePHP

By using __() we can create translatable strings in our applications. You can use placeholders as well in your translation strings. It is important to use place holders as parameters such as a name can move around in a sentance based on the language. Once you have added all the __() calls, you can use cake i18n extract -output app/locale. The generated file will be placed in app/locale/default.pot Mariano then gave an example and quick walkthrough of translation and i18n. He added translated elements to the views. Then extracted the strings with the shell and created translated values with poEdit.

Translating database content

Translate behavior helps to translate any database content. All translations in CakePHP are stored in one table. Translate behavior takes a number of fields when included on a model. This indicates which fields are going to be translated. Translated fields are not needed on the table schema. The translate behavior also allows you to specify a number of languages and language specific values or you can simply add one language. Later on another language can be added. The rest of Translate Behavior works seamlessly on find() and save(). When using elements with caching. You can use a key parameter when calling element() to ensure that different languages are cached separately. Mariano's talk brought the third day of CakeFest to an end. This has been an excellent conference so far and the last day promises to be great as well.

Martin Radosta - Record level security...

Martin's presentation was based around a behavior that he wrote to provide access control using SQL. In designing a solution, martin came up with a few criteria. The solution must be generic, it only requires 4 fields on any table that will be using the behavior. It should perform quickly and not create a lot of extra queries. The solution he searched for also needed to provide a few features. It should provide permissions for read write and delete. Permissions are assigned by role, with users having many roles. This system is similar to ACL but different, in that it stores the permissions for each record. Martin's behavior uses a permission system similar to the unix file system, with a owner, group, world access. This was implemented as series of bit masks. Unlike the unix filesystems, these permissions are summed and stored as one field. The 4 fields mentioned earlier are user_id, role_id, group_id, and permissions. These four fields allow the behavior to work, both the roles and groups also use binary values to reduce the number of columns. The binary values for roles and groups are compared to those in the role and group id for records . In addition the requested permission is combined with group and role values and checked against the permissions field. Since binary values are used, roles can be combined and will always be unique. Permissions in a system like this permissions are done via a bitmask system. User values for group, and role are compared to record permissions. If the value of the bitmask meets the expectation, the record is returned. In addition to a controller, an element, action in Appcontroller and a model are used. Martin gave a quick demo of an application using his behavior. The permissions checks are all done in the SQL of the behavior. Another interesting part of the behavior is that in the behavior's afterFind() extra values are added to indicate whether or not a user can write or delete. This allows for your interface to display the correct icons. Which is a nice added bonus. I personally was really impressed with how his system was designed and how it worked. He demonstrated how his fine grained access control group. He even had a root user that was not bound by the permissions system. The permissionYou can find this project at Sourceforge the project is licensed under the MIT license.

Fabian Andres - CakePHP in big compani...

Why talk about large companies. Larger companies have large demands and often they involve money over the internet. Large companies require fast and efficient applications, which in turn requires efficient tools. This is where CakePHP steps in. Current solutions for large merchant solutions include Java, and .Net solutions. In addition to these solutions, there are alternatives in PHP, ruby, python. However, rapid development is difficult in some of the popular solutions. By using an alternate solution you can tap into a large pool of developers worldwide. CakePHP helps in this area as well, as with a large community allows you to find developers to fill specific roles. CakePHP offers connectors for many databases. CakePHP also offers easy to use and efficient caching methods which help improve performance. There are many CakePHP sites run by large companies including Mozilla, Sony, Diesel, TV mallorca. Fabian then showed many of the websites that were mentioned in the presentation. Following this presentation there was a good discussion on caching and performance, and how to deal with high traffic situations.

Jeff Loiselle - Authentication & Autho...

Why authorize and authenticate? Authorization ensures someone is who they say they are. Restricting access is a separate process. Authorization is done in CakePHP with Auth Component. Auth works with a database by default, but it can be changed to work with anything. LDAP, Radius, and OpenID are some examples of alternate authentication sources. Auth component has a number of benefits. It hashes passwords, and it provides one API for all authentication sources.

Setting up AuthComponent

Need to setup a users table and create a user model. You should have a username and password field. This will help you make the most of the intelligent defaults built into Auth. After that you need to add Auth to you controllers var $components.

Acl component

Has an easy to use API, identifies, create nodes, checks permissions. The ACL component handles hierarchies with ease, which allows inheritance permission systems.

Auth modes and simple auth.

Auth component has a number of modes, each handles authorization in a different situation. Jeff did a live demo of setting up the ACL tables. Jeff setup the acl tables with cake acl initdb. After the acl tables were set up Jeff covered creating a simple login form and easy Auth.

Using Auth and Acl's together.

Before you can start using Auth and Acl together, you need some aros and acos. Jeff used his Acl management plugin to quickly create some aros and acos, as well as set the permissions for his new user and controllers. Jeff then demonstrated how to use to the AuthComponent in crud mode. Jeff ran out of time, but covered a few good options for handling Auth and ACL.

Jim Lerza - Origami - Automating the p...

Jim is from Expungement Assitance Services. They run clearMyRecord.com which helps people get their criminal records expunged. Origami is a proposed solution for automating criminal records relief in the United States. The application helps manage all the different types of forms that need to be filled out. All these forms need to be collected and standardized so that the data can be normalized. This helps to automate future applications, and streamline the the user experience. There was an existing application that had a pile of legacy code. This legacy code was partly written in mandarin, and had a difficult to understand naming convention. The database was a mess, and the identification system was jumbled and difficult to follow. There were many challenges and requirements that led them to choose CakePHP, including needed features, time, funding and other constraints. Their team faced a few Cake specific challenges. They had trouble with OOP practices, getting sandboxes setup, and some members of their team had challenges with the API documentation and the contents of the book. They also had difficulties figuring out how to implement specific features. Afterwards there was a quick demonstration of the clearMyRecord application and a sample form was filled out. Even though the team at EAS seemed to face a lot of challenges. Jim seemed to be fairly happy with their choice in frameworks, and would make the same choice again.

Ryan Petersen - Collective Intelligence

Collective intelligence is a shared or group intelligence that emerges from the collaboration and competition of many individual. Some examples would be Amazon's book recommendations. Netflix uses collective intelligence to track their stock and supply changes, and more accurately allocate their resources. Recommendations requires something to track like sales, or user preferences. A group of users is also required, the larger the group the better. A research survey found that a random sample of less that 1500 people will be the ideal and most efficient sample size. There are many ways to estimate preferences. The most simple and basic one is Euclidean distance scoring. Pearson Correlation Score, also uses 2 axis to plot out the points, this method is used by amazon and delicious.

Stochastic Optimization

Theory of being able to optimize things. Requires a cost function, it is the most important part of optimization as it gathers the dataset used. Ie. Execution time of a request, time used for data integrity, error handling/logging, client bandwidth, data queries/filtering. When doing metrics and calculating cost you can use a unit cost and parts to unit. This will allow you to control and manage the final output. Depending on what you are measuring, you need to control different weighting. Random searching is an inefficient process, as it is difficult to determine whether you are moving toward or away from where you want to be. Writing unit costing functions is a specific to the task you want to achieve. When doing optimization with cost optimization, you need to be aware of local minimums. Once you have reached a new minimum or optimized level you need to do additional testing by expanding the range in either direction. By expanding your test range you help to ensure that you have found a more accurate low cost point, and aim to ensure that you haven't found a local low point. Genetic Algorithms, and Hierarchal Grouping are other statistical methods to look into. Ryan is going to be releasing both Pearson Correlation and Euclid distance scoring will be released on the The bakery and SerenitySoft So check back for some code.

Martín Sarsale - Death of Apache Long ...

Lighttpd runs as one thread there are no forks, and only one thread. Lighttp is not good for large virtualhosts. It also bottlenecks on the disk speed. It is however good, when you have a single large application or need to total control. Lighttpd has several modules that are analogous to Apache such as Rewrite, Auth, Expires etc. Configuration files in lighttpd are very dynamic and allow for variables, regular expressions and if blocks. By using caching well you can reduce the number of requests made. By using Asset.timestamp = force you will get query strings that contain a querystring with the last modified datetime. You can use a configuration script to set the expiry time for these requests.

Lighttpd and PHP.

Lighttpd doesn't use a PHP module like Apache. Instead it connects to PHP via a socket or TCP/IP. Often this is done with FastCGI. This decoupling of PHP processor and webserver allows you to scale horizontally easily by adding more PHP servers. You can implement this with static resources as well. Static files can be easily routed to alternate machines based on regular expressions done in the config files. Unlike apache which handles and processes each request Lighttpd works more like a pipe connecting inputs to outputs, or between the client and the servers. LUA scripting is a simple scripting language that is built into lightttp. For example sending a random image. This can be done with raw PHP, PHP and X-Sendfile, or by using a LUA script. The LUA script is ~400% faster when compared to PHP. This demonstrates one of the many advantages that Lighttpd can offer over Apace There are similar performance gains to be made when using LUA scripts with full page caching. Lighttpd gives you a lot more control on how you configure your severs. You can easily fix problems with CPU use or HDD disk by adding more resources to the appropriate area. And since you can have multiple file servers attached to one Lighttpd process. Swapping out or adding extra disk server is not a difficult thing to do. Lighttpd seems like a viable and exciting alternative to Apache that I would consider using in the future.

Garrett Woodworth - CakePHP console ba...

Garret's talk focused on getting command line tools setup. Before getting started on that he covered how to setup a virtual host for a cake project. Once he got into the cake shell, he covered the basic core shells and how to call shells. Garret then used bake to create a new project and a database config file. Using cake bake project and cake bake db_config. Up next was creating a schema file with cake schema generate. The schema file was populated with a few tables to store some information about restaurants. A question was raised about adding and removing columns. Garret demonstrated that as well. Baking models controllers and views was up next. Using the previously created restaurants table, garret walked through baking a model, controller, and some views. At first a scaffold was used but the views were made concrete very quickly. The talk ended with a quick tour of the API and TestSuite shell, and how to look up different methods on different classes. Testing was up last and garret ran the freshly baked tests from the CLI. Garret will be continuing this talk later this week.

Mariano Iglesias - CakeFest.org: Theme...

Mariano is presenting about creating a complete website with a framework. Specifically Mariano will be talking the CakeFest site. This should help to show how to apply the theories that have been talked about up to today and throughout the rest of the week. cakefest.org was developed for the first Cakefest, it is multi-user, multi-event, multi-language application, that was needed to scale for mulitple events. It was built with Themes, Behaviors, pagination, security, Acl, Auth and i18n.

Using themes to 'reskin' a site

Themes are set by using Controller::$view = 'Theme'; and setting Controller::$theme = 'themeName'. The theme views allow you to override specific views and leave others as they are in the core application. In the CakeFest site the theme was tied to a url parameter. This allowed search engines to crawl and consume all of the content. A cookie would not allow that.

Behaviors

Behaviors were used to reduce and abstract much of the model code. Behaviors allow you to reuse code not only between models in this application but others as well. Mariano provided an example with the tokenaable behavior used in resetting passwords.

Security

You can use security to stop form manipulation, and force actions to only accept specific HTTP requests. For example using requireGet('login') will not allow a POST or any other request type other than GET to login. Security component automatically secures all forms built with form helper. A hash key is added to each form, and if the hash key doesn't match after post, the request is sent to a blackHole. Using the security component is an easy way to keep forms secure and safe.

Email Component

Email component was used to send emails from the CakeFest site. It used templates and attachments which are both native to the EmailComponent.

RSS and RequestHandler

By using RequestHandler and Router::parseExtensions() we don't need to add a separate action for the RSS and non RSS versions of the news listings. With this approach we also use a separate view file for the RSS format. Another benefit is that we are not required to set the headers manually or switch the layout. This helps to save time and effort, as the layout switching and header content types are generated automatically.

Nate Abele - PHP is dying

Nate started with a brief history of computation, starting with the abacus. And progressing to PHP and covering the presence of bad PHP and Perl code.

The good and bad of frameworks

Frameworks can help inexperienced developers write better code, however a framework can also be used in a black box context. As a tool that you use, you should try to understand how and why it works. Having a blackbox is not going to help you get better. If you want to use a tool and use it well you have to open it up. PHP still faces a number of challenges even after inexperienced developers are not included. These include a lack of namespaces, anonymous functions, closures. Many of these issues are solved by PHP 5.3. However, PHP is still dying becuase you can't overload operators. And it is just too simple. It requires only a few lines to generate output. Unlike a real language like Java or C++. It was a very tongue in cheek presentation, but it was well received and fun to watch.

Felix Geisendörfer - Git and CakePHP

Felix is a huge git fan and Git is a source version control application. It is a command line tool, and there are not many gui tools. Git has a few advantages, it is easier to integrate with other tools. Git also doesn't require a server, allowing you to work locally. Unlike svn there is only one .git folder and it contains the entire project history.

Configuring git

Before using git you should configure git with git config. You should configure your user name, user email and ui.color. Once you have configured git you are ready to go.

Making Commits

By using git add you can add single files, folders, whole trees. You then can use git commit to create a commit and add a commit message. You cannot store empty folders in git. If you have any empty folders you need to put an 'empty' file in the folders. find . -type f | grep -v empty | xargs git rm Felix used the above to clear all the temp files but leave the empty files. This will let you add the tmp directory structure to the git repo and still keep the directories clean.

The importance of SHA1 hashes

All objects in git are identified by SHA1. The SHA1 is used to identify commits, trees, and blobs. I also found it interesting that unlike SVN a git repo is very transparent. The commit SHA1's are actually the filenames in the repo. Although the contents of these files are compressed its nice to know there are files to look at instead of a pile of scary binary blobs.

Using .gitignore

.gitignore can be used to ignore files or paths. You should add files based on absolute paths from your project root. Normally with a cake setup you want to ignore app/tmp as well as your database.php. At this point Felix's excitement for git had to come to an end. His hour was up but I got the feeling that at least a few people had their interest in git increased. With the first day of CakeFest Argentina at a close I'm looking forward to the rest of the talks as today was an excellent start to what is shaping up to a great festival.

Guillermo Nuñez - MicroFormats in CakePHP

When html started being 'designed' presentation and structure muddled together and there was little semantic meaning attached. This html soup was found everywhere, even big sites like yahoo and google. Later styling and content was separated, making maintenance easier and making room to introduce of semantics. And while semantic markup works well for people. It doesn't help the computer understand the syntax and semantics of the information. Only the structure and importance. Web semantics and microformats allows authors to better describe the syntax and semantics of information to help the computers better understand our information. Microformats are part of this semantic solution. They allow the addition of semantic and syntactic information to HTML. As a transition to fully semantic code would be a difficult and lenghty process. There are many different microformats to handle different types of information, such as hCard for people, and hCalendar for events and dates. The use of microformats is invisible to the human user. However, they greatly improve the computers' ability to understand information. Microformats are implemented in a few clients. The operator extension for firefox will allow automatic parsing and retrieval for microformats. Microformats also enhance usability for people with accessibility issues. Guillermo Nuñez then presented a prototype browser / browser plugin that creates additional accessibility links for microformat data, such as adding 'call' button to make a skype call from the browser. In addition to this a helper for creating microformats. As a side note this presentation was done in spanish, and my hat is off to the translation people as it was a very well done and seamless experience for a non spanish speaker.

Nate Abele - RESTFUL CakePHP

Why would you want to create RESTful application interface? A webservice/RESTFUL interface will allow you to create a public interface that allows 3rd party sites to integrate with your applications. RESTful API's allow you to provide open services for your customers. This helps customers by giving them choice in what service they use, and reduces a customer's feeling of being locked into one service. By providing open access to data through webservices you not only benefits your customers, it also benefits you company as well. An open webservice can help attract developers to implement and use your webservice with their application. Webservices are important to developers as it helps reduce the effort and time needed to make applications work, and makes code easier to maintain. Nate compared different RESTful/webservices solutions, covering SOAP and some of the troubles created by its implementation. SOAP's problems stemmed from its heavy XML payload and single point of access. REST was covered next, and Nate extolled the advantages of REST and how it provides more useful information in the headers. This decreases request size and increases the clarity of what is actually being requested. REST also makes it easier to create CRUD api's. REST favours using the existing HTTP methods over creating method calls in your request bodies. And uses all of the HTTP methods to implement a CRUD interface. You can easily add REST funtionality to your application with only a few changes. You need to add Router::parseExtension() and add the RequestHandler to your components. This will enable requests like posts/view/1.xml. You then need to add additional view paths for any other extensions you may need. To allow for alternate views you simply need to add an views/posts/xml directory would enable xml views tied to your xml requests. Using Router::mapResources('posts'); will allow you to make GET/POST/PUT/DELETE requests to posts/1.xml and the appropriate action will be triggered. Issues with scaling were raised in regards to REST api's. CakePHP REST implementation scale very well in a horizontal fashion thanks to the way PHP works. Nate stated that the biggest challenge to scaling are still going to be on the Database and latency side, unlike other platforms.

We Bake with CakePHP