Category: PHP

Installing gearmand, libgearman and pecl gearman extension for php from source in Debian 6 & 7

I had a pretty rough evening today. No, not because the waiter forgot to add sugar in my tea, but because it was so boring to go through the trial and errors of installing gearman daemon and pecl gearman extension for php.

First I tried with the pretty-obvious-awe-fucking-some way.

[sourcecode language=”shell”]
apt-get update
apt-get install gearman
pecl install gearman
[/sourcecode]

In above steps, “apt-get install gearman” ran smoothly. But then “pecl install gearman” failed saying that it doesn’t have libgearman. Eh? so I installed libgearman4 (in Debian Squeezy. It was libgearman6 in Wheezy) and libgearman-dev. But pecl failed again to compile the extension saying that libgearman is missing. Strange! So I googled about this issue and found that it could be a link error where a symbolic link might be required of “/usr/include/libgearman” as “/usr/include/libgearman-1.0″. Still no luck.

So I decided to compile gearmand from the source. And libgearman is also included with that, so it will fix two errors at once. I downloaded the latest gearman package from launchpad and tried to compile it

[sourcecode language=”shell”]
wget https://launchpad.net/gearmand/1.2/1.1.11/+download/gearmand-1.1.11.tar.gz
tar -zxvf gearmand-1.1.11.tar.gz
cd gearmand-1.1.11
./configure
[/sourcecode]

Failure 1:
At this step, configure stopped showing the following error

[sourcecode language=”shell”]
configure: error: cannot find Boost headers version >= 1.39.0
[/sourcecode]

To fix this, I had to install “libboost-all-dev” by following command
[sourcecode language=”shell”]
apt-get install libboost-all-dev
[/sourcecode]

And I tried to compile gearman and it failed again

Failure 2:
At this step, configure stopped showing that it cannot find gperf. That’s fine – I have installed gperf and tried to configure gearman again

[sourcecode language=”shell”]
apt-get install gperf
[/sourcecode]

Failure 3:
Now it failed again, showing that libevent is missing. Hmm! Had to fix it anyway

[sourcecode language=”shell”]
apt-get install libevent-dev
[/sourcecode]

Failure 4:
Heck! Another failure. Now it’s showing that it can’t find libuuid. This part was a little tricky to solve, but finally fixed with the following package

[sourcecode language=”shell”]
apt-get install uuid-dev
[/sourcecode]

Let’s configure again. And sweet that the configure script ran smoothly. Let’s compile using make

Failure 5:
Grrr! At this point the make script failed with a bunch of text, where the following lines were at the top

[sourcecode language=”shell”]
libgearman/backtrace.cc: In function ‘void custom_backtrace()’:
libgearman/backtrace.cc:64:6: sorry, unimplemented: Graphite loop optimizations can only be used if the libcloog-ppl0 package is installed
[/sourcecode]

So it cannot find a library named libcloog-ppl. Let’s fix this problem by

[sourcecode language=”shell”]
apt-get install libcloog-ppl-dev
[/sourcecode]

Now I’ve tried to run the make script, and it was good. So i also ran make install to complete the installation.

[sourcecode language=”shell”]
make
make install
[/sourcecode]

Now gearmand and libgearman both are installed. So I tried to install pecl-gearman with the following extension and voila! it worked. No more missing libgearman anymore.

[sourcecode language=”shell”]
pecl install gearman
[/sourcecode]

Now all I had to do is add the line “extension=gearman.so” in my php.ini .

The process was tedious and boring and took me more time than writing this article. If you have seen “Despicable Me 2” when Lucy and Gru went to ElMacho’s restaurant and were attacked by that crazy chicken and finally Lucy exclaimed “What’s wrong with that chicken!”

I really wanted to say “What’s wrong with this chicken” after gearman was installed at last.

Enjoy!

QuickTip: Turn symfony's web profiler debug bar on or off

Check out your config_dev.yml and you will notice a special section over there

[sourcecode language=”shell”]
web_profiler:
toolbar: true
intercept_redirects: false
[/sourcecode]

You can turn the debug bar on or off anytime by changing the value of toolbar in this web_profiler section.

If you want to turn debug bar off for a specific controller action, you can do so by the following line. This will actually stop the profiler for the current action.

[sourcecode language=”php”]
$this->container->get(‘profiler’)->disable();
[/sourcecode]

Enjoy!

Install and Run Symfony 2.3.6 projects in OpenShift instances in just one minute with this boilerplate repository

Okay, I have written an article 2 days ago where I went through every details. But today. I have created a blank symfony container with all the necessary deploy hook and mods so that you can get your symfony 2 project up and running in an openshift container within a minute, fully automated, seriously!

Github Repo: https://github.com/hasinhayder/openshift-symfony-2.3.0

Just create a new ZendServer 5.6 or PHP 5.3 gear from your OpenShift control panel and while creating, supply this git repository’s checkout URL (https://github.com/hasinhayder/openshift-symfony-2.3.0) in the “Source Code” field. That’s it. And oh by the way, don’t forget to add a MySQL cartridge later in this gear. You don’t have to do anything else at all! The deploy script will take care of everything.

howtouseit

Here’s a quicktip just for the first time ssh login. You may not have to do it at all, but if by any chance you cannot connect to mysql database from app/console then all you need to do is clear the cache and you are done 🙂

[sourcecode language=”shell”]
cd $OPENSHIFT_REPO_DIR/php
php app/console clear:cache –env=dev
[/sourcecode]

Now Symfony can be installed in just one minute in your openshift instances. Enjoy!

By the way, if you are wondering how did I manage to load OpenShift MySQL credentials automatically in the container, then open the app/config/config.yml and you will notice that I have imported a new file named “params.php” from the same directory

[sourcecode language=”shell”]
# app/config/config.yml
imports:
– { resource: parameters.yml }
– { resource: security.yml }
– { resource: params.php }
[/sourcecode]

and in the app/config/params.php I have added these lines which injects the database parameters in the container with appropriate value

[sourcecode language=”php”]
<?php
# app/config/params.php
$container->setParameter(‘database_host’, getEnv("OPENSHIFT_MYSQL_DB_HOST"));
$container->setParameter(‘database_port’, getEnv("OPENSHIFT_MYSQL_DB_PORT"));
$container->setParameter(‘database_name’, getEnv("OPENSHIFT_APP_NAME"));
$container->setParameter(‘database_user’, getEnv("OPENSHIFT_MYSQL_DB_USERNAME"));
$container->setParameter(‘database_password’, getEnv("OPENSHIFT_MYSQL_DB_PASSWORD"));
?>
[/sourcecode]

Update: This repo is now a part of OpenShift Quickstarts and you can directly access and instantly deploy it from here https://www.openshift.com/quickstarts/symfony-236, as well as from PHP Section in your OpenShift app control panel

Screen Shot 2013-10-28 at 10.41.08 PM

How to login a user programatically in Symfony2

Sometime, you may need to log in an user manually from code, instead of generic form based log in. To do it, you need to use Two Security component “UsernamePasswordToken” and “InteractiveLoginEvent”. We will also use another exception object “UsernameNotFoundException” if the user is not found.

[sourcecode language=”php”]
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
[/sourcecode]

Now from your controller, you can login an user like this

[sourcecode language=”php”]
$em = $this->getDoctrine();
$repo = $em->getRepository("UserBundle:User"); //Entity Repository
$user = $repo->loadUserByUsername($username);
if (!$user) {
throw new UsernameNotFoundException("User not found");
} else {
$token = new UsernamePasswordToken($user, null, "your_firewall_name", $user->getRoles());
$this->get("security.context")->setToken($token); //now the user is logged in

//now dispatch the login event
$request = $this->get("request");
$event = new InteractiveLoginEvent($request, $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
}
[/sourcecode]

Dispatching the “security.interactive_login” is important, because then every listeners which are bound to this event will work appropriately. But the actual login happens when you call setToken(…). Also make sure that you pass the correct firewall name which you had defined in your security.yml.

You can also recall the logged in user any time using the following code

[sourcecode language=”php”]
//anywhere
$user = $this->get(‘security.context’)->getToken()->getUser();

//or from a controller
$user = $this->getUser();
[/sourcecode]

That’s it. Hope you will find it handy 🙂

Get a list of Top 10 authors in a WordPress blog, and sort them by firstname and last name

Getting top 10 authors’s list from WordPress is actually pretty simple with a SELECT query. Here is the SQL for that which sorts the list by number of posts of each authors
[sourcecode language=”sql”]
SELECT wp_users.id,
display_name,
user_login,
user_nicename,
count(wp_posts.id) AS number_of_posts
FROM wp_users
JOIN wp_posts
ON wp_posts.post_author = wp_users.id
GROUP BY wp_posts.post_author
ORDER BY number_of_posts DESC
LIMIT 10
[/sourcecode]

And sorting this list by first name is pretty simple as well
[sourcecode language=”sql”]
SELECT *
FROM (SELECT wp_users.id,
display_name,
user_login,
user_nicename,
count(wp_posts.id) AS number_of_posts
FROM wp_users
JOIN wp_posts
ON wp_posts.post_author = wp_users.id
GROUP BY wp_posts.post_author
ORDER BY number_of_posts DESC
LIMIT 10) AS SortedByCount
ORDER BY display_name
[/sourcecode]

However, sorting that list by Lastname is a little tricky, we need to take extra care for display_name and extract the last name from it.
[sourcecode language=”sql”]
SELECT *
FROM (SELECT wp_users.id,
display_name,
user_login,
user_nicename,
count(wp_posts.id) AS number_of_posts,
substring_index(display_name, ‘ ‘, -1) AS lastname
FROM wp_users
JOIN wp_posts
ON wp_posts.post_author = wp_users.id
GROUP BY wp_posts.post_author
ORDER BY number_of_posts DESC
LIMIT 10) AS SortedByCount
ORDER BY lastname
[/sourcecode]

Now all you need to do is run it like this
[sourcecode language=”php”]
$top_authors = $wpdb->get_results($sql, ARRAY_A);
[/sourcecode]

Sweet, eh?

Improving UX in the WordPress Admin Panel with Interactive Meta Boxes

Our goal is simple today, we want to add interactivity to our boring metaboxes. Instead of showing lots and lots of irrelevant input boxes at once, we will properly group them into different metaboxe containers and then display the required one based on the action of another one.

We will create a custom post called “profession”, then we will let our user choose from two pre defined professions, for example “photographer” and “programmer”. Based on his choice we will display another set of metaboxes to get the details of that profession.

Step 1: Register the custom post
Here is a simple custom post register script, add the following snippet in your functions.php

[sourcecode language=”php”]
add_action( ‘init’, ‘mytheme_custom_post_profession’ );
function mytheme_custom_post_profession() {

$labels = array(
‘name’ => _x( ‘Professions’, ‘profession’ ),
‘singular_name’ => _x( ‘Profession’, ‘profession’ ),
‘add_new’ => _x( ‘Add New’, ‘profession’ ),
‘all_items’ => _x( ‘Professions’, ‘profession’ ),
‘add_new_item’ => _x( ‘Add New Profession’, ‘profession’ ),
‘edit_item’ => _x( ‘Edit Profession’, ‘profession’ ),
‘new_item’ => _x( ‘New Profession’, ‘profession’ ),
‘view_item’ => _x( ‘View Profession’, ‘profession’ ),
‘search_items’ => _x( ‘Search Professions’, ‘profession’ ),
‘not_found’ => _x( ‘No professions found’, ‘profession’ ),
‘not_found_in_trash’ => _x( ‘No professions found in Trash’, ‘profession’ ),
‘parent_item_colon’ => _x( ‘Parent Profession:’, ‘profession’ ),
‘menu_name’ => _x( ‘Professions’, ‘profession’ ),
);

$args = array(
‘labels’ => $labels,
‘hierarchical’ => false,
‘public’ => true,
‘show_ui’ => true,
‘show_in_menu’ => true,
‘supports’ => array( ‘title’, ‘thumbnail’),
);

register_post_type( ‘profession’, $args );
}
[/sourcecode]

Step 2: Add the necessary libraries in your theme/plugin
Creating metaboxes is a tedious and boring task. So we will take help of one of the fantastic metabox libraries out there. We will be using Custom-Metabox-Framework which is also widely known as “CMB”. It will make our code a lot less cluttered. So download (or checkout) the library, unzip and rename the folder as “cmb” and place it inside your theme folder. Now add the following code in your functions.php

[sourcecode language=”php”]
add_action( ‘init’, ‘mytheme_initialize_cmb_meta_boxes’ );
function mytheme_initialize_cmb_meta_boxes() {
if ( !class_exists( ‘cmb_Meta_Box’ ) ) {
require_once( ‘cmb/init.php’ );
}
}
[/sourcecode]

Step 3: Create some metaboxes for this profession custom post
Now we have all the necessary tools available, lets create three metaboxes and attach them with only this “profession” type custom post.

[sourcecode language=”php”]
function mytheme_profession_metaboxes( $meta_boxes ) {
$prefix = ‘_mytheme_’; // Prefix for all fields
$meta_boxes[] = array(
‘id’ => ‘profession_details’,
‘title’ => ‘Profession Details’,
‘pages’ => array(‘profession’), // post type
‘context’ => ‘normal’,
‘priority’ => ‘high’,
‘show_names’ => true, // Show field names on the left
‘fields’ => array(

array(
‘name’ => ‘Your Name’,
‘id’ => $prefix . ‘name’,
‘type’ => ‘text’
),
array(
‘name’ => ‘Profession Type’,
‘id’ => $prefix . ‘profession_type’,
‘type’ => ‘select’,
‘options’=>array(
array("name"=>"Select a Profession","value"=>0),
array("name"=>"Photographer","value"=>1),
array("name"=>"Programmer","value"=>2),
)
),
),
);

$meta_boxes[] = array(
‘id’ => ‘profession_photographer’,
‘title’ => ‘Some details of your <b>photography</b> job’,
‘pages’ => array(‘profession’), // post type
‘context’ => ‘normal’,
‘priority’ => ‘high’,
‘show_names’ => true, // Show field names on the left
‘fields’ => array(
array(
‘name’ => "Your Camera",
‘id’ => $prefix . ‘photography_camera’,
‘type’ => ‘text_medium’
),
array(
‘name’ =>"Your primary interest is",
‘desc’ => ‘Landscape/Portrait/Street/Lifestyle’,
‘id’ => $prefix . ‘photography_interest’,
‘type’ => ‘text_medium’
),
),
);

$meta_boxes[] = array(
‘id’ => ‘profession_programmer’,
‘title’ => ‘Some details of your <b>programming</b> job’,
‘pages’ => array(‘profession’), // post type
‘context’ => ‘normal’,
‘priority’ => ‘high’,
‘show_names’ => true, // Show field names on the left
‘fields’ => array(
array(
‘name’ => "Your Favorite IDE",
‘id’ => $prefix . ‘programming_ide’,
‘type’ => ‘text_medium’
),
array(
‘name’ =>"Your primary language",
‘desc’ => ‘C/PHP/Java/Python/Javascript’,
‘id’ => $prefix . ‘programming_lang’,
‘type’ => ‘text_medium’
),
),
);

return $meta_boxes;
}

add_filter( ‘cmb_meta_boxes’, ‘mytheme_profession_metaboxes’ );
[/sourcecode]

At this point, if we click on “New Profession” from our WordPress admin panel, we will see the editor screen like this. Please notice that we have already disable the “editor” field while registering this custom post (using the “supports” attribute)

The Profession Screen

Uh, oh! that looks very confusing for people of both professions. I mean asking the photographer about their favorite language and ide is utter nonsense, and vice versa. So How can we make sure that only photographers will see the second metabox container, and programmers will see the third metabox container? Lets do this!

Step 4: The Magical Ingredient: Adding the interactivity using Javascript
We need to add some javascript at this point to improve the user experience at this point. Create a new javascript file inside the “js” folder inside your theme folder. Name the file as “profession-admin.js”. Now we need to make sure that this file is loaded properly in the admin panel.

[sourcecode language=”php”]
function mytheme_admin_load_scripts($hook) {
if( $hook != ‘post.php’ && $hook != ‘post-new.php’ )
return;

wp_enqueue_script( ‘custom-js’, get_template_directory_uri()."/js/profession-admin.js" );
}
add_action(‘admin_enqueue_scripts’, ‘mytheme_admin_load_scripts’);
[/sourcecode]

Now open the js/profession-admin.js and add the following code. Please keep in mind that jQuery is loaded in wordpress admin panel by default, and it works in no-conflict mode. So we want code like this if we want to use our favorite $ as a reference to the jQuery object.

[sourcecode language=”javascript”]
(function($){
$(document).ready(function(){
$("#profession_photographer").hide();
$("#profession_programmer").hide();

//lets add the interactivity by adding an event listener
$("#_mytheme_profession_type").bind("change",function(){
if ($(this).val()==1){
// photographer
$("#profession_photographer").show();
$("#profession_programmer").hide();
}else if ($(this).val()==2){
//programmer
$("#profession_photographer").hide();
$("#profession_programmer").show();
} else {
//still confused, hasn’t selected any
$("#profession_photographer").hide();
$("#profession_programmer").hide();
}
});

//make sure that these metaboxes appear properly in profession edit screen
if($("#_mytheme_profession_type").val()==1) //photographer
$("#profession_photographer").show();
else if ($("#_mytheme_profession_type").val()==2) //programmer
$("#profession_programmer").show();

})
})(jQuery);
[/sourcecode]

At this moment, when you click on the “New Profession” you will see like this.
Improved Profession Screen

And if you select a profession, the appropriate metabox will be displayed instantly.
Photography

That looks good eh? So what did our javascript do? Lets have a look at the things it does

  • It passes the jQuery object to our function as $
  • It hides all the secondary metaboxes related to the professions
  • It registers a new event listener that monitors the change event in our profession select box
  • It displays the appropiate metabox when someone picks a profession
  • It also displays the correct metabox when someone edits a profession

So that’s mainly it. We have made our profession screen look much better. And we are now collecting details about the particular profession without confusing people from other professions. And most of all, it is much friendlier than before 🙂

I hope you have enjoyed this article and already started planning to implement it in your next wordpress project. Have fun!

Shameless Plug
If you are looking for a fantastic NGinx+PHP-fpm based WordPress hosting with Solid Performance, give WPonFIRE a try. You will never be disappoint at all. And if you want a 25% discount coupon for life, let me know in the comment and I will arrange you one.

WPonFIRE Premium WordPress Hosting for Everyone

Limit number of posts an user can create in WordPress admin panel

If you, by any chance, want to limit the number of posts an user can create in your multi author WordPress blog, there is a nice way to do it. Add the following code in your theme’s functions.php file

[sourcecode language=”php”]
add_action("load-post-new.php","limit_user_by_post_count");
function limit_user_by_post_count(){
$user = get_current_user_id();
if (!current_user_can( ‘manage_options’)) {
//not an admin – so impose the limit
$user_post_count = count_user_posts($user);
if($user_post_count>=10)
header("Location: /wp-admin/edit.php");
}
}
[/sourcecode]

In this example, if the user has 10 posts he/she can not create a new post anymore. Every time he clicks on the “New Post” menu, he will be redirected to “All Posts” page. But the “admin” will not be limited at all 🙂

Sweet, eh?

Running Symfony 2 Applications in OpenShift

Openshift is a fantastic Polyglot PaaS from Redhat, and you can do a lot of things with these containers. The good news is that with free accounts, OpenShift gives three gears for free, forever. Today, in this article I will show you how to install and run your Symfony applications in OpenShift.

After you have created your free account in OpenShift, go to the applications page and create a new “Zend Server 5.6” application. You can choose “PHP 5.3” containers as well, but there are many benefits of choosing ZendServer.

Before we dive into the details, please MAKE SURE that you have added your public key in your openshift settings section. This is very important that you do this.

So after creating the new ZendServer 5.6 application and adding our public key in our OpenShift account, this is time to check out from our application’s git repository. OpenShift gives you a private git repository for every application and you can find the url in the right side of your application details.

Screen Shot 2013-10-24 at 8.15.05 PM

Now, follow these steps to check out this git repository and create a blank symfony application inside it’s php directory. You should have composer installed in your machine before this step.

[sourcecode language=”shell”]
git clone ssh://[email protected]/~/git/sym.git/
cd sym/php
rm -fr *.php
composer create-project symfony/framework-standard-edition ./
[/sourcecode]

After it runs, you have a blank symfony project installed inside this php directory. Now you need to add these files and commit in the git repository

[sourcecode language=”shell”]
git add -A
git commit -am "Blank Symfony Project"
git push
[/sourcecode]

OpenShift has an auto deployment feature which will deploy your application code after you push it in the git repo. It makes the deployment a lot easier for everyone.

Now you can visit your openshift container’s url but hey, why there is a blank screen? To find the answer of this question you need to open the .gitignore file. By default it’s content is like this

[sourcecode language=”shell”]
/web/bundles/
/app/bootstrap.php.cache
/app/config/parameters.yml
/app/cache/*
/app/logs/*
/vendor/
!app/cache/.gitkeep
!app/logs/.gitkeep
/build/
/bin/
/composer.phar
[/sourcecode]

Notice those lines “/app/config/parameters.yml” and “/vendor/”? These lines mean that parameters.yml file and everything in the vendor folder will be excluded from your commit. For now, just remove the line where it says about parameters.yml and keep the vendor line as is. So your final .gitignore file will look like this

[sourcecode language=”shell”]
/web/bundles/
/app/bootstrap.php.cache
/app/cache/*
/app/logs/*
/vendor/
!app/cache/.gitkeep
!app/logs/.gitkeep
/build/
/bin/
/composer.phar
[/sourcecode]

Now come to the root of your openshift repo and give this commands in the terminal

[sourcecode language=”shell”]
git add -A
git commit -am "Parameters.yml"
git push
[/sourcecode]

Now we need to setup the database details. To get those credentials, you need to log into your openshift gear. You can find the ssh login details in the right side of your app settings. In the following screenshot, you can get the mysql details (username and password) and ssh login details from the right side “Remote Access” section. Just click on the “Show Password” and “Want to login” links.

Screen Shot 2013-10-25 at 11.24.32 AM

After you get the Remote Access , log into your openshift gear from your terminal. Once you are logged in, type the following commands in the terminal.

Screen Shot 2013-10-25 at 11.29.17 AM

Copy the values of mysql db host and port. Now we have all the data for our symfony app. Open your parameters.yml file and put all the essential data. For my one, it looks like this

[sourcecode language=”shell”]
parameters:
database_driver: pdo_mysql
database_host: 127.7.119.2
database_port: 3306
database_name: symfony
database_user: MuHaHaHa
database_password: "4s89-vh55G6q"
mailer_transport: smtp
mailer_host: 127.0.0.1
mailer_user: null
mailer_password: null
locale: en
secret: WhateverYouLikeTo
[/sourcecode]

Now commit this file and push

[sourcecode language=”shell”]
git commit -am "Parameters"
git push
[/sourcecode]

At this point, we need to write a deploy hook which will do the following things everytime you push your code.

  • It checks if composer is installed in our openshift gear. If not, it installs it
  • It then go to $OPENSHIFT_REOP_DIR/php folder and run composer install command
  • Then it gives write permission to app/cache and app/logs folder

Open your openshift repo, go to the .openshift folder, then go to the action_hooks folder and create a new file named deploy. Inside that file, put the following content

[sourcecode language=”shell”]
#!/bin/bash
# .openshift/action_hooks/deploy

export COMPOSER_HOME="$OPENSHIFT_DATA_DIR/.composer"

if [ ! -f "$OPENSHIFT_DATA_DIR/composer.phar" ]; then
curl -s https://getcomposer.org/installer | /usr/local/zend/bin/php — –install-dir=$OPENSHIFT_DATA_DIR
else
/usr/local/zend/bin/php $OPENSHIFT_DATA_DIR/composer.phar self-update
fi

unset GIT_DIR
cd $OPENSHIFT_REPO_DIR/php
/usr/local/zend/bin/php $OPENSHIFT_DATA_DIR/composer.phar install

chmod -R 0777 $OPENSHIFT_REPO_DIR/php/app/cache
chmod -R 0777 $OPENSHIFT_REPO_DIR/php/app/logs
[/sourcecode]

As a sidenote, if you are using regular PHP 5.3 containers instead of ZendServer 5.6, then replace “/usr/local/zend/bin/php” with “/usr/bin/php” in the deploy script above.

Save this file and give it executable permission by following command from your terminal

[sourcecode language=”shell”]
chmod +x deploy
[/sourcecode]

Now come to the root of your openshift repo and commit this deploy file. OpenShift supports different git hooks and you can check out https://www.openshift.com/developers/deploying-and-building-applications to know more about those.

[sourcecode language=”shell”]
git add -A
git commit -am "Deploy Hook"
git push
[/sourcecode]

You will notice some magical things happening at this point. After you push, you will notice in your terminal that composer is being installed in your openshift gear, and then it runs the composer install in appropriate directory.

Now visit your optnshift url (url/web/app_dev.php). Strange! now it is showing a strange error that we don’t have access to this app_dev.php. To fix this, open our app_dev.php (openshift repo/php/web/app_dev.php) and comment out line #12 to #18, I mean comment the following lines in your app_dev.php.

[sourcecode language=”php”]
//php/web/app_dev.php
if (isset($_SERVER[‘HTTP_CLIENT_IP’])
|| isset($_SERVER[‘HTTP_X_FORWARDED_FOR’])
|| !in_array(@$_SERVER[‘REMOTE_ADDR’], array(‘127.0.0.1’, ‘fe80::1’, ‘::1’))
) {
header(‘HTTP/1.0 403 Forbidden’);
exit(‘You are not allowed to access this file. Check ‘.basename(__FILE__).’ for more information.’);
}
[/sourcecode]

Sweet, now visit your openshift gear’s url (url/web/app_dev.php) and you can see that symfony is running smoothly :). But wait a minute – the URL contains the “web” part which looks ugly. All openshift PHP gear’s document root is set to $OPENSHIFT_REPO_DIR/php folder, which is in this case the root of our symfony application. But we don’t want this “web” in the URL. To do that, just create a .htaccess file in the “php” directory in our local openshift repo and put the following content

[sourcecode language=”shell”]
#php/.htaccess
RewriteEngine on
RewriteCond %{HTTP_HOST} ^your-openshift-domain$ [NC,OR]
RewriteCond %{REQUEST_URI} !web/
RewriteRule (.*) /web/$1 [L]
[/sourcecode]

And we are done, visit your openshift URL (url/app_dev.php) and it will working like a charm. So what if we want to set this app_dev.php as the default endpoint for our application? which means that we don’t even need to put “app-dev.php” in our url. To do that, open the .htaccess file from your “web” folder and replace all instance or “app.php” and “app\.php” to “app_dev.php” and “app_dev\.php” respectively. Then save your repo and make a git push and you are done! Tada!!!!

Hope you’ve enjoyed this long article. 🙂

Followup: I have automated the whole process and created a boilerplate Symfony 2.3.0 repository. Now you can get up and running in just one minute. Check out http://hasin.me/2013/10/27/install-and-run-symfony-2-3-0-in-openshift-instances-in-just-one-minute-with-this-boilerplate-repository/

Shameless Plug
Did you check our latest Onepage parallax portfolio template in Themeforest?
01_sonnet_preview.__large_preview

Playing with Parse.com API

Screen Shot 2013-10-23 at 9.29.51 PM

I’ve started using Parse.com API not more than a week ago, and I already fall in love with it. The first thing that hit me was “whoa, no extra work for storing objects in my database” and that’s really it. Saving data was never easier. Parse.com’s javascript API, the documentation is very good and it will help you to start your project in no time. Beside diving into the details, let me highlight another cool feature of Parse.com API. It’s the user management. Sign up someone, or let someone sign in, validate their email? Everything is there!

’nuff said, how to start?
Go to https://parse.com/apps, register a new application and copy the application key and javascript key.

Now open your html file, add the Parse.com’s js library
[sourcecode language=”html”]
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
[/sourcecode]

and now initialize your Parse.com application
[sourcecode language=”javascript”]
Parse.initialize("Application ID", "Javascript Key");
[/sourcecode]

That’s it. Now you are ready to play with the rest of this article.

Sign me up, pronto!
One of the most tedious, boring work while developing an application is to deal with registration, email validation, ACL and taking care of the signing in process. With Parse.com API this is pretty straight forward. To sign up a new new user, all you gotta do is the following one!

[sourcecode language=”javascript”]
var user = new Parse.User();
user.set("username", "ElMacho");
user.set("password", "chicken");
user.set("email", "[email protected]");

user.signUp(null, {
success: function(user) {
// Everything’s done!
console.log(user.id);
},
error: function(user, error) {
alert("Error: " + error.code + " " + error.message);
}
});
[/sourcecode]

Your user is signed up! If you need to validate user’s email then log into your Parse.com dashboard and from your application’s settings section turn on the email validation. It’s simple.

Alright, let me in!
Alright, your users have signed up .Now let them get in. It’s simple to write a sign in script with Parse API

[sourcecode language=”javascript”]
Parse.User.logIn("ElMacho", "chicken", {
success: function(user) {
console.log(user.get("email"));
},
error: function(user, error) {
console.log("you shall not pass!");
}
});
[/sourcecode]

But hey, does an user have to login everytime? No, not at all. The logged in user’s state is saved in browser. So before attempting to sign in him/her again, you can check if he is already logged-in.

[sourcecode language=”javascript”]
var loggedInUser = Parse.User.current();
if(!loggedInUser){
//off you go, perform a log in
} else {
console.log(loggedInUser.get("email"));
}
[/sourcecode]

easy, eh?

Interesting, how can I deal with data?
Okay, enough with signing up and signing in. Lets save some data. Say, for example, we want to store user’s favorite books in Parse.com’s datastore. We will also retrieve the list later.

To save some data in Parse.com, we need to write code like this
[sourcecode language=”javascript”]
var user = Parse.User.current();
var Book = Parse.Object.extend("favoritebooks");
var b1 = new Book({"name":"King Solomon’s Mine","user":user});
b1.save();

var b2 = new Book({"name":"Return of She","user":user});
b2.save();
[/sourcecode]

While saving an object you can also take care of the error or success state.

[sourcecode language=”javascript”]
var b1 = new Book({"name":"King Solomon’s Mine","user":user});
b1.save(null, {
success:function(b){
console.log("successfully saved")
},
error:function(b,error){
console.log(error.message);
}
});

[/sourcecode]

You can save as many Books/data as you want, and link them up with the current user. Linking like this is useful for retrieving them in future. As we have a few saved records, lets pull them and see if they are really saved.

[sourcecode language=”javascript”]
var Book = Parse.Object.extend("favoritebooks");
var q = new Parse.Query(Book);
q.equalTo("user",user);
q.find({
success: function(results){
for(i in results){
var book = results[i];
console.log(book.get("name"));
}
}
});
[/sourcecode]

Once it runs, you can see that it outputs currently logged in user’s favorite books. Pretty neat, eh?

like equalTo, there are a dozen of useful constraints which you can use with your query. You can get the complete list at https://parse.com/docs/js_guide#queries-constraints . Parse.com’s documentation is pretty solid, and you will find almost everything over there.

It’s dinner time, log me out!
Simple, just call Parse.User.logOut() and you are done!

So is it just about user management and saving data?
No!, not at all!. But saving data and managing credentials + ACL are one of the coolest features that you can do with Parse.com API. Beside these object storage, you can host your application (ExpressJS based), you can run your code in the cloud (Background Job, Cloud Code), take care of the push notifications and even upload and store binary files.

In overall, Parse.com’s API is super cool. Give it a try today, you will love it for sure. And by the way, there is a super handy data browser in your application dashboard, use that!

Launching of WPonFIRE, the premier managed WordPress hosting for everyone

wponfire-banner

Today me and my partner Patrick have launched WPonFIRE, our WordPress based startup. If you are struggling with the performance of your wordpress blog, or spending too much because of some vague pageview based pricing model of your current provider – you may want to host with us. We will host your wordpress blog in a managed, fine tuned, Nginx based environment. We will be monitoring for the spikes, and honestly, there will always be someone listening to your emails, chitchats and try our best to satisfy the requirement.

At this moment, our plans are starting at $19/mo and the highest one is $99/mo. And if you choose yearly plans, we will be generous to give you 2 months for free.

WPonFIRE boxes are properly stress tested, because we really want to make sure that you will get premium return for your every penny, and your viewers will never be disappointed. If you want to integrate your blog with CDN, we can help you with that too. And guess what, based on your current setup you may even qualify for a free migration service. And migration services are usually expensive elsewhere, may cost you up to $500!

Anyway, to supercharge your WordPress blog please give us a shot. You will not be disappointed, promise!