Skip to content

Feed aggregator

Policeman Takes $22K From Innocent Driver

Paul M. Jones - Tue, 05/15/2012 - 22:48
Reby was driving down Interstate 40, heading west through Putnam County, when he was stopped for speeding. A Monterey police officer wanted to know if he was carrying any large amounts of cash. "I said, ‘Around $20,000,’" he recalled. "Then, … Continue reading →
Categories: Blogs

PHPMaster.com: Using SPL Iterators, Part 1

PHPDeveloper.org - Tue, 05/15/2012 - 18:26

On PHPMaster.com today there's a new tutorial posted, the first part of a series, looking at the use of the Standard PHP Library (SPL) in PHP. In this first part of the series, Stefan Froelich looks specifically at two of the more common uses for iterators - working with arrays and directories.

When I first came across the term iteration and saw the overwhelming list of classes related to it in the SPL, I was taken aback. It seemed maybe iteration was too complex for me to grasp. I soon realized it was just a fancy word for something we programmers do all the time. [...] In the first part of this two-part series I'll introduce you to iteration and how you can take advantage of some of the built-in classes from the Standard PHP Library (SPL).

Included in the tutorial is example code showing how to use the ArrayIterator to work with an array and the DirectoryIterator to process the contents of a directory. He also briefly touches on a few other iterators like "FileExtensionFilter", "RecursiveDirectoryIterator" and "RecursiveArrayIterator".

Categories: Blogs

MaltBlue.com: Zend Form Mastery with Zend_Config - Part 2, Core Form Configuration

PHPDeveloper.org - Tue, 05/15/2012 - 17:04

In his previous post to the MaltBlue.com blog Matt introduced the concept of configuration-driven Zend_Form instances. He's back with a second part to the series, enhancing his original examples by covering some of the base-level form configuration settings.

Ok, this should have been part one, but irrespective, here's the second installment in zend form mastery with zend config - core form configuration. As the W3c Form spec says, there are 8 attributes applicable to forms.

These attributes, including "action", "name" and "onsubmit", can all be set easily in the XML-based configuration file. He includes an example of the full XML file to show how they all fit together (updated from part 1). You can see an example of the output here and can grab the source for the example from github.

Categories: Blogs

Sean Coates' Blog: PHP as a templating language

PHPDeveloper.org - Tue, 05/15/2012 - 16:58

In this new post to his blog Sean Coates talks about PHP as a templating language and why he (and Gimmebar) have decided to go another, more frontend-based direction.

For many years, I was a supporter of using PHP as a templating language to render HTML. However, I really don't buy into the idea of adding an additional abstraction layer on top of PHP, such as Smarty (and many others). In the past year or so, I've come to the realization that even PHP itself is no longer ideally suited to function as the templating engine of current web applications - at least not as the primary templating engine for such apps.

His reasoning is pretty simple - more and more web applications are becoming less and less server-driven. When building applications (and APIs) you don't know how the data will be consumed, so your frontend has to be agnostic. So, what's his current alternative of choice? The Mustache templating framework provides a simple way to create reusable templates (along with the compatible Handlebars Javascript library).

Categories: Blogs

Getting Started with MongoDB and PHP

Nearly 3 years ago I discovered a new database that literally changed my life. I know, that’s a pretty bold claim, but it’s true. While leading the engineering team at OpenSky I faced a problem I was well familiar with. How to build a e-commerce product that: 1. Provided performance and scale 2. Handled many verticals and 3. Provided proper indexing on key attributes. In search for a...
Categories: Communities

Fabien Potencier's Blog: Sami: Yet another PHP API documentation generator

PHPDeveloper.org - Tue, 05/15/2012 - 15:18

Fabien Potencier has released a new tool to the open source community today - a documentation generation tool called Sami.

Nowadays, phpDocumentor version 2 is probably the best option out there as it has a good architecture, it works fine, it is extensible, and quite a few big PHP projects is already using it. And that's fine. I don't want to compete with it, I don't want to replace it, I'm just open sourcing some code used by Symfony, Twig, and Silex because I'm not comfortable with closed-source software. And to be totally honest and transparent, I have not released the code before because it was not "good enough".

He gives an example of how to install and use Sami - configuring the directories to parse and setting up a custom theme for the resulting generated documentation (using regular CSS and HTML definitions).

Categories: Blogs

Voices of the ElePHPant Podcast: Interview with Derick Rethans

PHPDeveloper.org - Tue, 05/15/2012 - 14:22

The Voices of the ElePHPant podcast has released their latest episode - an interview with Derick Rethans of 10gen and XDebug fame.

Cal's "three questions" for Derick involve

  • How did you come up with the idea and how did the project get started?
  • What's been the most fun and interesting part about building the community around XDebug?
  • What's the hardest lesson you've learned about running a project like XDebug?

You can listen to this latest episode either via the in-page player or by downloading the mp3 directly. You can also subscribe to their feed to get the latest as they're released.

Categories: Blogs

My Brain Can’t Handle OOP Anymore

The other week I was working on my compilers homework – the semantic analysis part is an object-oriented nightmare. Something called the visitor pattern to traverse trees and do weird stuff. Preview Text:  In object-oriented programming everything gets muddled together. Functions are bundled with data, everything is codependent and there’s no...
Categories: Communities

TSA Gropes Henry Kissinger

Paul M. Jones - Tue, 05/15/2012 - 04:51
Kissinger, who was in a wheelchair, was told by a TSA agent that he needed to be searched. “He stood with his suit jacket off, and he was wearing suspenders,” freelance reporter Matthew Cole told the Post. “They gave him … Continue reading →
Categories: Blogs

Jeremy Cook's Blog: Implementing IteratorAggregate and Iterator

PHPDeveloper.org - Mon, 05/14/2012 - 19:04

In a recent post to his blog Jeremy Cook has gotten back into looking at some of the SPL functionality that comes with PHP. In this new post he looks specifically at the IteratorAggregate and Iterator object types.

After a bit of a break I'm finally able to get back to writing about the predefined interfaces in PHP. PHP provides two interfaces that allow you to define how your objects behave in a foreach loop: IteratorAggregate and Iterator. Before taking a look at IteratorAggregate I'll briefly discuss how we can iterate over objects in PHP 'natively' and what it means to be Traversable.

He introduces the concepts being being "iteratable" and "traversable". He then shows how to implement the IteratorAggregate (only one method required, "getIterator") and Iterator ("next", "valid", "current" and "key" methods required) in classes of your own.

You can find out more about these two object types (including more sample usage) on their manual pages: IteratorAggregate & Iterator.

Categories: Blogs

Marcelo Gornstein's Blog: Making your ivr nodes (call) flow with PAGI

PHPDeveloper.org - Mon, 05/14/2012 - 18:09

Marcelo Gornstein has returned to his "IVR with PHP" series in this latest post (see others here and here). In this new post he shows you how to create a full flow of interaction for your callers:

The last article was about how to create call flow nodes for asterisk, using pagi and php, to easily create telephony applications. It's now time to add a layer on top of it, and create a complete call flow with several nodes.

He talks about NodeControllers to control execution flow, results from their execution, available actions and an example of creating a controller and adding nodes. He builds on this simple controller and shows how to handle a few actions including responding to user feedback, adding multiple menu options and some more complex logic using a closure to contain the functionality.

Categories: Blogs

Lukas Smith's Blog: Query parameter handling in Symfony2

PHPDeveloper.org - Mon, 05/14/2012 - 17:56

Lukas Smith is looking for feedback about a question that's been in his mind a lot lately - can the handling of query parameters be made better for the Symfony2 framework (and even easier to use).

Obviously you can already access query parameters today already but it could be easier. Essentially what I want is a way for developers to easily configure what query parameters they expect and what values they expect. This is useful for several things like easier reading and validating of query parameters, self documenting API both for API docs for humans but also for machines.

He's asking for feedback and ideas from the community on a proposed solution that could make things more flexible. He also briefly mentions the route matching and how qurey parameters could cause them not to match:

For one I don't think that a mismatch on a route requirement of a query parameter cause the route to not match. However then it can quickly become confusing for the end user or it would require adding more and more syntax to handle all the different cases.
Categories: Blogs

Gonzalo Ayuso's Blog: Building a simple SQL wrapper with PHP

PHPDeveloper.org - Mon, 05/14/2012 - 16:17

In this new post to his blog Gonzalo Ayuso has shared a simple SQL wrapper that he uses to work with his databases. It takes in an injection of the database connection component (a href="http://php.net/pdo">PDO) and provides functionality for inserts, updates, etc. with transaction support.

If we don't use an ORM within our projects we need to write SQL statements by hand. I don't mind to write SQL. It's simple and descriptive but sometimes we like to use helpers to avoid write the same code again and again. Today we are going to create a simple library to help use to write simple SQL queries.

It's a lightweight library that'd be good for basic uses, but when you start getting into something a bit more complex, something like Doctrine2 or Propel might be a better solution (or whatever your framework of choice has built in).

Categories: Blogs

PHP 5.4 by examples

Aren't you already tired of listing PHP 5.4 features to colleagues and having to demonstrate them? In this article I'll include all the code samples you need to make them get a feel for the new use cases.ArraysLet's start with something not invasive and nice to look at: array syntax similar to JSON's. Preview Text:  Aren't you already tired of...
Categories: Communities

User Auth with CakePHP 2.1 – part 3

nuts and bolts of cakephp - teknoid - Fri, 05/11/2012 - 15:33

As promised in the previous part we’ll take a look at the admin section.

If you remember, we’ve setup our users so that when they create an account, they are inactive by default and cannot login into the app.

app/Controller/AppController.php

$this->Auth->authenticate = array(
            'all' => array (
                'scope' => array('User.is_active' => 1)
            ),
            'Form'
        );

Since our freshly created users have is_active = 0 we’ll need to create an admin page where one would be able to approve inactive users.
Let’s see how we’ll act in the admin role.

In part 1, we’ve setup prefix routing and our app is ready to accept admin logins.
This is our login() method again:

public function login() {
            if ($this->request->is('post')) {
                if ($this->Auth->login()) {
                    if ($this->Auth->user('is_admin')) {
                        return $this->redirect(array(
                            'controller' => 'users',
                            'action' => 'index',
                            'admin' => true
                        ));
                    } else {
                        return $this->redirect('/');
                    }
                } else {
                    $this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
                }
            }
        }

And here’s a relevant view, just in case:

<?php
    echo $this->Form->create();
    echo $this->Form->inputs(
        array(
            'username',
            'password'
        )
    );
    echo $this->Form->end('Submit');
    echo $this->Html->link('Don\'t have an account? Register now!', array(
        'controller' => 'users',
        'action' => 'add'
    ));
?>

If we look at the redirect() method in the above login() it presumes that we have an admin_index() action.
Let’s create one:

public function admin_index() {
            $users = $this->paginate($this->User, array(
                'User.is_active' => 0
            ));
            $this->set(compact('users'));
        }

The goal is to display (paginate) inactive users, so that an admin can approve them… simple enough.
I’m not going to cover pagination setup here, as it is very simple, covered nicely in the manual and would be beyond what we need consider for now.

Anyways, let’s build a simple view to display our inactive users:

<?php if (isset($users) && !empty($users)) : ?>
   <?php foreach ($users as $user) : ?>
    <div>
        <?php echo $user['User']['username']; ?>
        <?php
            echo $this->Html->link('Activate', array(
                'controller' => 'users',
                'action' => 'user_activate',
                'admin' => true,
                 $user['User']['id']
            ));
        ?>
        <?php
            echo $this->Html->link('Edit', array(
                'controller' => 'users',
                'action' => 'user_edit',
                'admin' => true,
                 $user['User']['id']
            ));
        ?>
    </div>
   <?php endforeach; ?>
<?php endif; ?>

Next to each username we’ll show an “Activate” and “Edit” links.
Ultimately the “Activate” link we’ll be something like example.com/admin/users/user_activate/345. This should change the user status with ID = 345 from inactive to active.
Here’s the method to do so:

public function admin_user_activate($id = null) {
            if ($id) {
                $this->User->id = $id;
                if ($this->User->saveField('is_active', 1)) {
                    return $this->redirect(array(
                        'controller' => 'users',
                        'action' => 'index',
                        'admin' => true
                    ));
                }

            }
        }

All we are doing is updating is_active field to “1″ for a given user $id.
Now the user has been approved and we redirect the admin back to the index page.

Let’s recap:

  1. We’ve setup basic Auth to allow users to login and register in the system
  2. We’ve added a check so that only active users can login
  3. We’ve setup admin/prefix routing to allow for creation of admin-only resources
  4. We’ve added a check so that only admins can access the above resources
  5. And finally, we’ve added the ability for admins to activate the users

p.s. Here’s a simple chunk of code that creates a “Log in/Log out” link so that users can act accordingly. You’ll probably want to add this to your layout or a relevant element.

<?php
echo $this->Session->check('Auth.User')
?
$this->Html->link(
             'Log out',
              array(
                 'controller' => 'users',
                 'action' => 'logout',
                 'admin' => false
              ))
:
$this->Html->link(
              'Log in',
               array(
                  'controller' => 'users',
                  'action' => 'login'
               ));
?>

With a simple check for presence of the Auth.User key (this is where Auth stores information about logged-in users) we know if the user is logged-in or not into the system, and by using a quick ternary operator we display either a “Log out” or “Log in” links.

The end.

Categories: Blogs

User Auth with CakePHP 2.1 – part 2

nuts and bolts of cakephp - teknoid - Thu, 05/10/2012 - 15:06

CakePHP 2.1

Now that we’ve completed our basic setup for Auth, let’s take a look at the User.php model…

class User extends AppModel {

    public $validate = array(
      'username' => array(
          array(
            'rule' => 'notEmpty',
            'message' => 'Username cannot be empty'
          ),
          array(
            'rule' => 'isUnique',
            'message' => 'This username is already taken'
          )
      ),
      'password' => array(
          array(
            'rule' => 'notEmpty',
            'message' => 'Password cannot be empty'
          ),
          array(
            'rule' => array('minLength', 4),
            'message' => 'Must be at least 4 chars'
          ),
          array(
            'rule' => array('passCompare'),
            'message' => 'The passwords do not match'
          )
      )
    );

    public function passCompare() {
        return ($this->data[$this->alias]['password'] === $this->data[$this->alias]['password_confirm']);
    }

    public function beforeSave() {
        $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
        return true;
    }
}

Nothing terribly interesting… we’ve got our validation rules setup and just a few simple methods to handle the rest.
Let’s go in reverse a little. Keep in mind that the new Auth system in CakePHP doesn’t hash passwords by default. This is actually great news for old-timers, because the work-arounds and somewhat hacky solutions we had to do in 1.x (just to deal with password comparison, for example) are gone and are now replaced with a single line of code in your beforeSave() method.
(I hope you see which one). By using AuthComponent::password() we encrypt the user’s password with a default hashing algorithm.
Thus the password is safely hashed in the DB and we do so just prior to saving the record (remember to always return true;) in the beforeSave() or nothing will be… saved).

Speaking of password comparison, you’ll notice that in our validation rules we have a custom method passCompare(). Because I’m lazy and too much typing leads to headaches, a simple one liner will take care of our needs. If passwords match the method will return true, else it will return false and that’s all we really need to validate or invalidate the given field.

For now this covers our User.php model.

Let us take a look at some interesting things in the UsersController.php.

public function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow(array(
       'add', 'account_created'
    ));
}

We will allow two methods in our UsersController.php to be accessible by non-authorized (not logged-in) users.
Of course, it would be silly not to allow users to register their account, thus we allow add() method… also we’ll have a simple action account_created(), which is not going to do much of anything for the time being.

Alright, let’s take a look at the relevant add() method:

public function add() {
            if ($this->request->is('post')) {
                if ($this->User->save($this->request->data)) {
                    $this->Session->setFlash(__('Account created. An admin will need to activate it.'), 'default', array(), 'auth');
                    return $this->redirect(array(
                        'controller' => 'users',
                        'action' => 'account_created'
                    ));
                }
            }
        }

All we do here is accept the data from a form, validate it (by using the save() method) and if all goes well, we redirect the user to the “account created” page.
Remember all that prefix/admin routing we’ve setup before?
Well, as you can see our user is going to live in the system, but remain inactive until an admin logs-in and activates her. Recall 'scope' => array('User.is_active' => 1)… freshly created account will have is_active = 0, so without admin approval nobody is getting in.

Let’s take a quick look at the add.ctp view:

<?php
    echo $this->Form->create();
    echo $this->Form->inputs(
        array(
            'username',
            'password',
            'password_confirm' => array(
                'type' => 'password'
            )
        )
    );
    echo $this->Form->end('Submit');
?>

As you can see I really went all out here… three fields: username, password, and password_confirm. Now compare these fields to the validation rules in our User.php model and you should see how the whole thing is coming together. I kept the example purposely oversimplified to just show how the data will be POST’ed from the form to the controller’s add() method, validated by the User.php model (with password hashing) and thereafter saved to the DB.

To wrap things up for part 2 of this tutorial, let’s take a look at the login() and logout() methods (also in the UsersController.php).

public function login() {
            if ($this->request->is('post')) {
                if ($this->Auth->login()) {
                    if ($this->Auth->user('is_admin')) {
                        return $this->redirect(array(
                            'controller' => 'users',
                            'action' => 'index',
                            'admin' => true
                        ));
                    } else {
                        return $this->redirect('/');
                    }
                } else {
                    $this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
                }
            }
        }

The interesting thing about this method is the check for admin. if ($this->Auth->user('is_admin')) { ... , so if the user is an admin we redirect them to example.com/admin/users/index (this is all part of prefix/admin routing). To tell cake, which “route” it should take we supply 'admin' => true. Of course, this presumes that we’ll have an admin_index() method in the UsersController.php. As you see, all other users simply get redirected to the “/” (root) of your website.

The logout() method is as simple as could be:

public function logout() {
            $this->redirect($this->Auth->logout());
        }

In the next part we will take a look at the admin side of things and some little things like a login/logout link, which you’d expect in any site that has user Auth.

Categories: Blogs

Pure vs Practical REST

This is a useful table I often go back to, comparing pure REST (such as HATEOAS) with the "practical" REST so often found in the field: Preview Text:  This is a useful table found by Mark O'neill that you may find yourself going back to often, comparing pure REST (such as HATEOAS) with the "practical" REST so often found in...
Categories: Communities

Ibuildings techPortal: Conference Report: Whisky Web

PHPDeveloper.org - Wed, 05/09/2012 - 18:09

For those that couldn't attend this year's Whiskey Web conference and were wondering what it was like, you should check out this new summary from Marco De Bortoli on the Ibuildings techPortal.

Whisky Web is a brand new, fresh conference and the 2012 edition was the inaugural event, with hopefully many more to follow. This event has some familiar names from the PHP community behind it, Juozas "Joe" Kaziukėnas and his helpers Michael Maclean, Max Manders, Dale Harvey and Paul Dragoonis.

He talks about several of the sessions including the keynotes from Josh Holmes and David Zuelke and other sessions covering things like estimation, Node.js, the rush into new technologies, testing legacy code and running applications in "the cloud".

Categories: Blogs

User Auth with CakePHP 2.1 – part 1

nuts and bolts of cakephp - teknoid - Wed, 05/09/2012 - 17:34

CakePHP 2.1

The example application in the CakePHP book does a very good job of covering setup and implementation of a basic Auth system.
Let’s continue building on that and cover a few other things, by adding a couple of more features and looking at some of the other things in more detail.

Good to say that cake started separating authentication and authorization as of 2.x release. While these concepts always go hand-in-hand, I feel it created a bit of confusion for beginners, because while separate in theory they were not clearly separate in implementation.

As always, your main players when it comes to Auth is AppController.php and User.php.
(Of course, UsersController.php is not to be forgotten about…)

Let’s go ahead and start with app/Controllers/AppController.php:

class AppController extends Controller {
    public $components = array('Auth', 'Session');

    public function beforeFilter() {
        $this->Auth->authorize = array('Controller');
        $this->Auth->authenticate = array(
            'all' => array (
                'scope' => array('User.is_active' => 1)
            ),
            'Form'
        );
    }

    public function isAuthorized($user) {
        if (($this->params['prefix'] === 'admin') && ($user['is_admin'] != 1)) {
            return false;
        }
        return true;
    }
}

First, as always we will include the necessary components. For the time being it’s just: public $components = array('Auth', 'Session');.

Authorization is going to be controller-based. Meaning, we will tell CakePHP to authorize (let users access resources) based on the Controller actions.
(It’s nice that you can now specify such setting directly in the $components array, but I kept it in the beforeFilter() to show a slightly different approach).

Next, comes our Authentication setup. Unlike Authorization, which answers who is allowed to get to what, Authentication checks if the user is indeed who she claims to be (handle login/logout).

We’ll be using good ol’ login form, thus the 'Form' key in our setup.
Moving on, I’ve added a “scope” of User.is_active => 1… this presumes that in our users table we have a field called is_active and therefore only active users can access the application (everybody whose is_active status is equal to 0 is denied by default). More on this a little further.

isAuthorized() is a sweet little method, which helps us to fine-tune our permissions.
The implementation is truly up to your needs, but let’s see what we’ve got going on in this example…

public function isAuthorized($user) {
   if (($this->params['prefix'] === 'admin') && ($user['is_admin'] != 1)) {
      return false;
   }
   return true;
}

The basic premise here is that an admin can access admin-related resources within the app. (We’ll get into prefix routing setup a little further down the line).
The presumption is that we have an is_admin field in our users table and if the user is not an admin $user['is_admin'] != 1 she cannot access any resource that has an “admin” prefix… again more on that a little later.
Otherwise, for all average Joe’s, we say return true; access whatever you want (once authorized) as long as it’s not an admin-related resource.

Alright then, let’s take a look at the prefix routing.
The setup couldn’t be simpler just un-comment the following in your app/Config/core.php.
Configure::write('Routing.prefixes', array('admin'));

This concludes our basic setup. We’ll take a look at the User.php model as well UsersController.php in the next part, which is coming soon here.

p.s. For those who wish to play around with the setup, here’s all you’d need to get started with the users table.

DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
  `password` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
  `is_admin` tinyint(1) DEFAULT '0',
  `is_active` tinyint(1) DEFAULT '0',
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Categories: Blogs