Category: PHP

Working with combined expressions in WHERE clauses in Laravel 4

laravel-combined

When retrieving records from tables in our database, you often have to write combined expressions in WHERE clauses like

[sourcecode language=”sql”]
SELECT * FROM users WHERE status=1 AND (fname = ‘John’ OR lname=’Doe’)
[/sourcecode]

The query above is pulling out all users who’s status is set to 1, and fname is equal to ‘John’ or status is 1 and lname is equal to ‘Doe’. Now this query is significantly different from the following one.

[sourcecode language=”sql”]
SELECT * FROM users WHERE status=1 AND fname = ‘John’ OR lname=’Doe’
[/sourcecode]

Can you tell us what can go wrong with a statement like this? Well to find out more, let’s have a look at how this query will be parsed by database engine

[sourcecode language=”sql”]
SELECT * FROM users WHERE (status=1 AND fname = ‘John’)

OR

SELECT * FROM users WHERE lname=’Doe’
[/sourcecode]

So this query will pull every record that has a status set to 1 and fname equivalent to ‘John’. Then, with the previously pulled records, it will also pull all the users who has a lname equal to ‘Doe’, but this time it will pull out all users disregarding their status. Which means that users with status = 0 or 1 or 2 will also be in the resultset. I bet that is not what you were looking for while you’re writing this query and clearly understands the difference between these two queries. So you got the point of grouping or combining logical expressions and the impact that can have in your resultset. Writing a combined logical expression is easy in SQL. But what if you’re told to do the same operation using Laravel 4’s built in ORM which is called Eloquent ORM. It’s a little tricky to do the same operation in eloquent because of this combined expression, and it needs an anonymous function 🙂 Let’s have a look at the following code in our User model

[sourcecode language=”php”]
static function searchByName($fname, $lname){
return User::where("status", 1)
->where(function ($query) use ($fname, $lname) {
$query->where("fname", ‘=’, $fname)
->orwhere("lname", ‘=’, $lname);
})
->get([‘*’]);
}
[/sourcecode]

Now searchByName(…) function will work as we expected. You can try the following one and see the difference and notice how it is VERY MUCH different from our expectation

[sourcecode language=”php”]
static function searchByName($fname, $lname)
{
return User::where("status", 1)
->where("fname", ‘=’, $fname)
->orWhere("lname", ‘=’, $lname)
->get([‘*’]);
}
[/sourcecode]

Eloquent ORM’s where function can make use of callbacks in this way. Please note how we used anonymous function as callback that also uses $fname and $lname from the arguments. That’s mainly it. I hope that you’ve enjoyed this article 🙂

Picking up random elements from DOM using jQuery

tumblr_n1zv0cTukw1tubinno1_1280

Selecting a group of DOM elements is super duper easy these days using CSS selectors, or a particular element via their ID. But what about picking up a random element from these group of elements? In this article I am going to show you how to do it by extending jQuery

Let’s consider that we have the following markup. Now we will pick a random button and change it’s value

[sourcecode language=”html”]
<div class="container">
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
</div>
[/sourcecode]

Let’s extend jQuery and add a random() function to it

[sourcecode language=”javascript”]
$.fn.random = function() {
return this.eq(Math.floor(Math.random() * this.length));
}
[/sourcecode]

Now we can pick up a random button and change it’s value quite easily.

[sourcecode language=”javascript”]
$(".container button").random().html("Click Me");
[/sourcecode]

That was easy, eh? Hope you’ll like it.

How to enable some useful text formatting options in TinyMCE in WordPress

tumblr_na06t4fnlI1tubinno1_1280

Most of the time default TinyMCE editor in WordPress is pretty adequate for everyday text formatting. However, there are a lot of extra formatting options which are hidden out of the box. Enabling these options will give you extra formatting features that will be useful for many of us. In this article, I will show you how to enable these hidden formatting options in TinyMCE. Just add the following code block in your theme’s functions.php file

[sourcecode language=”php”]
function tinymce_enable_more_buttons($buttons)
{
$buttons[1] = ‘fontselect’;
$buttons[2] = ‘fontsizeselect’;
$buttons[3] = ‘styleselect’;
return $buttons;
}

add_filter("mce_buttons_3", "tinymce_enable_more_buttons");
[/sourcecode]

Now you can see these extra options in the editor as shown in the animation below.

format

Hope you liked this article.

Find n number of posts randomly from a group of categories in WordPress

tumblr_n2hutxfrNr1tubinno1_1280

When you are developing a theme, or maybe writing a plugin, it is often required to display related posts in single posts page. These related posts are fetched by various criteria. Sometimes they are fetched from the same categories a post belongs to, or by tags. Sometimes they are set by the author of the posts.

In this article I am going to show you how to fetch the categories of a particular post, and then fetch some random posts from these categories. It’s not as tough as you’re thinking.

Fetch the categories of a post
You can quickly fetch the categories assigned to a particular post using get_the_category() function. Let’s have a look at the following code block

[sourcecode language=”php”]
$post_id = 1234;
$categories = array();
$_categories = get_the_category($post_id);
foreach ($_categories as $_cat) {
$categories[] = $_cat->term_id;
}
[/sourcecode]

Now you have the array of category ids which are assigned to a particular post with post id “1234”.

Fetch posts from these same categories
Now we are going to fetch some posts from these categories fetched in step 1. We will use kinda less documented category__in and post__not_in parameters with get_posts() function. We will make sure that the post “1234” doesn’t come in the list of random posts. Because it will be silly to display that same post as a relative.

[sourcecode language=”php”]
$args = array(
‘orderby’ => ‘rand’, //important to fetch random posts
‘post_type’ => ‘post’,
‘numberposts’ => 3,
‘post__not_in’ => array($post_id), //exclude the same post
‘category__in’ => $categories,
‘post_status’=>’publish’
);
$related_posts = get_posts($args);
[/sourcecode]

Now you have an array of 3 related posts, which are related to the post “1234” by belonging in the same categories. Their properties are described in details here in this Codex Article

That was easy, wasn’t it? Hopefully you will find it useful in your next WordPress theme project. Good night.

Passing data from PHP to the enqueued scripts in WordPress

tumblr_nau9zqjZay1tubinno1_1280

Enqueueing scripts, while being as one of the most common tasks for WordPress theme and plugin developers, has a very nice companion feature that can be used to pass data to it. These data will then be available in the native scope of those scripts. In this short article, I am going to show you how to to this

Remember the first parameter of wp_enqueue_script() function? It’s called ‘handle’, and works as a reference point. We need this handle to send some data to it with the help of wp_localize_script() function. Let’s have a look at the following example.

[sourcecode language=”php”]
add_action("wp_enqueue_scripts","my_scripts_loader");

function my_scripts_loader(){
$data = array("home"=>site_url());

wp_enqueue_script("myscript","path/to/my/script.js");
wp_localize_script( "myscript", "blog", $data );

}
[/sourcecode]

wp_localize_script() takes the handle of the script file, a variable name and an array. Finally, wp_localize_script converts that array into a JSON object and makes available in the local scope of that javascript file via that variable name. So, from the example above you can write the following code in your script.js and it will show you your blog URL, which was actually passed to it using wp_localize_script function

[sourcecode language=”javascript”]
alert(blog.home);
[/sourcecode]

This feature is pretty handy for developing themes and plugins, to pass data from your PHP scripts to the external javascript files. Hope you’ve enjoyed this article.

How to enqueue javascript files properly in the WordPress admin panel

You’d probably have answered the question already, won’t you? We all know that the correct answer is to do that we have to write a function that hooks the “admin_enqueue_scripts” and inside that function we will have to load the script via wp_enqueue_scripts() function. That’s the correct answer, but when it comes to the best practices, it fails. Because when you’re loading a javascript file blindly in all pages, it can be messy and it also may conflict with other scripts which are already loaded in that page. Besides that, why load an extra script everywhere when you actually need it in a specific page, or two perhaps.

The correct, or “precise” way to enqueue a javascript file in the WordPress admin panel is to check first which page you’re on. And when you’re on that specific page where this javascript file is actually required, load it. So how you’re gonna check which page you’re on in the admin panel? The enqueue hook passes a parameter that tells you about this. Let’s have a look at the following example

[sourcecode language=”php”]
add_action("admin_enqueue_scripts","admin_scripts_loader");

function admin_scripts_loader(){
wp_enqueue_script("myscript","path/to/my/script.js");
}
[/sourcecode]

There is nothing wrong with the enqueueing system above. However, the only problem is that it will load your script in every admin page, you need it or not. So let’s write a better version of that admin_scripts_loader function.

[sourcecode language=”php”]
function admin_scripts_loader($hook){
if(in_array($hook,array("post-new.php","post.php","edit.php"))) {
//specifically load this javascript in post editor pages
wp_enqueue_script("myscript", "path/to/my/script.js");
}
}
[/sourcecode]

Now the code is more accurately loading your javascript file only in the post editor pages. This $hook variable gives you the name of the PHP file that you’re on. So it’s quite easy for you to figure out where you should load it.

Hope you enjoyed it.

Fetch WordPress media files using BackboneJS

WordPress uses BackboneJS and Underscores in the admin panel. Though codex has a rich set of documentation on different WordPress topics, it lacks instructions of using these BackboneJS models in your code. So here’s a small snippet which shows you how to fetch an attachment from your WordPress blog using these models

First of all, you will have to enqueue media scripts via wp_enqueue_scripts or admin_enqueue_scripts hook. This will load all the necessary media js scripts needed for this task.

[sourcecode language=”php”]
wp_enqueue_media();
[/sourcecode]

And then, from your front end code you can access the attachments like this

https://gist.github.com/hasinhayder/eb62a4c02bf4134f5939

Hope you liked it 🙂

ReduxFramework – a perfect example of how not to redesign your site!

This is not a rant. It’s a post from a fan who is sad, very sad.

I am a fan of Redux Framework and use it in all my themes. It’s easy to use and it has an excellent collection of controls which can make your life easier when you deal with option panels. However, the documentation SUCKS!!! It SUCKS big time. Not because it lacks necessary information, but because how it gives you the exact feeling of finding a needle in the haystack. If you go to their documentation, you will literally feel lost. Why not try to search the documentation of “color” control, or “text” perhaps”.

It was a lot easier to find the required information when they were using github wiki. But now, with the redesign, it’s very tough.  Their search doesn’t work as expected, gives you a lot of unnecessary information that you don’t need.

And oh, the funny thing is that in the WHOLE site, their github repository is not linked (as of the time of writing it). You simply can’t find a “DOWNLOAD” button, not even something that takes you to the original ReduxFramework repo! Heh, I submitted a ticket in their issue tracker and Dovy replied that he will take care of it. Maybe he is too busy to add a link in 3 months!

So go to ReduxFramework site, and scream “Where is the Mothe*fuck*ng  download/fork link?”. No one will hear your scream, boy, no one. They are too busy in making PAID extensions.

I love ReduxFramework. I don’t like how it gives a negative impression from the website. I really don’t like that.

 

Upgrading PHP to 5.5 in a CentOS 6 server with Vesta CP

Vesta CP comes with PHP 5.4 by default. If you want to upgrade it to 5.5, follow these steps

1. Stop Apache and Remove current PHP
[sourcecode language=”shell”]
service httpd stop
yum -y remove php
[/sourcecode]

2. Add remi repository
[sourcecode language=”shell”]
#For 32 Bit OS
wget http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
rpm -Uvh remi-release-6*.rpm epel-release-6*.rpm

#For 64Bit OS
wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
rpm -Uvh remi-release-6*.rpm epel-release-6*.rpm
[/sourcecode]

3. Enable Remi Repository
open /etc/yum.repos.d/remi.repo and add 1 beside enabled for both [remi] and [remi-php55], as shown in the screenshot
Screen Shot 2014-06-03 at 8.44.47 PM

4. Install PHP 5.5
[sourcecode language=”shell”]
yum -y install php php-bcmath php-cli php-common php-gd php-imap php-mbstring php-mcrypt php-mysql php-pdo php-soap php-tidy php-xml php-xmlrpc php-pecl-apc phpMyAdmin roundcubemail php-opcache php-xdebug
[/sourcecode]

Step 5: Cleanup, linking and finishing
[sourcecode language=”shell”]
mv -f /etc/php.ini.rpmsave /etc/php.ini
mv -f /etc/roundcubemail/db.inc.php.rpmsave /etc/roundcubemail/db.inc.php
mv -f /etc/roundcubemail/main.inc.php.rpmsave /etc/roundcubemail/main.inc.php
mv -f /etc/phpMyAdmin/config.inc.php.rpmsave /etc/phpMyAdmin/config.inc.php
mv -f /etc/httpd/conf.d/roundcubemail.conf.rpmsave /etc/httpd/conf.d/roundcubemail.conf
mv -f /etc/httpd/conf.d/phpMyAdmin.conf.rpmsave /etc/httpd/conf.d/phpMyAdmin.conf
service httpd start
[/sourcecode]

And you’re done 🙂 Enjoy!

Remote deploy your project using git's server side hooks

6Icr9fARMmTjTHqTzK8z_DSC_0123
Git hooks are very useful to perform tasks during different states of the codebase. Sometime you can cancel your commit if jshint throws some error on your javascript files, or you can deploy your current working directory somewhere in the server. In this article we will be discussing how to deploy code using git’s server side hooks.

Step 1: Add a git repository somewhere in your server
Create a blank git repository somewhere in your server. For example, see the following code

[sourcecode language=”shell”]
cd /path/to/your/folder
git –bare init myrepo.git
[/sourcecode]

You will see that a new directory named myrepo.git has been created. Inside that folder you will find a few other folders named “hooks”, “branches” and so on. However, sometime, this command may give you unexpected result by creating those child folders outside the myrepo.git. In that case the following commands are helpful

[sourcecode language=”shell”]
cd /path/to/your/folder
mkdir myrepo.git
cd myrepo.git
git –bare init
[/sourcecode]

Now everything will be inside this myrepo.git folder. Lets move to the next step.

Step 2: Add this newly created git repo as a remote to your current project
This part is easy, just follow these commands from inside your current project. We are going to add the repository we created in step 1 as a remote named “server”

[sourcecode language=”shell”]
cd /your/current/project/directory
git remote add server ssh://user@serveraddress/path/to/your/folder/myrepo.git
[/sourcecode]

Once added, you can push to this git repo like you did with origin, like
[sourcecode language=”shell”]
git commit -am "Some Commit Message"
git push server master
# (or simply git push server)
[/sourcecode]

You may want to add your local machine’s public key in the ~/.ssh/authorized_keys file so that you won’t have to input username and password every time you push your code.

Step 3: Add the git hook
To deploy your code after a push, we need to deal with post-receive hook. Log into your remote server and go to the repository that we had created in step 1 (i.e /path/to/your/folder/myrepo.git). Now go to the hooks directory and create a file named post-receive. If you want to deploy your code to a directory accessible by web server, for example /usr/share/nginx/www/myproject then the code of post-receive will be like this

[sourcecode language=”shell”]
#!/bin/bash
export GIT_WORK_TREE=/usr/share/nginx/www/myproject
git checkout -f
[/sourcecode]

The code above will checkout current HEAD of master branch inside the directory specified by GIT_WORK_TREE. But sometime, you may have another project which is cloned from your git repo. In those directories, instead of checking out, we will do a git pull. So our post-receive file’s code will be like this

[sourcecode language=”shell”]
#!/bin/bash
cd /usr/share/nginx/www/myproject
unset GIT_DIR
git pull
[/sourcecode]

remember to unset GIT_DIR which is very important for a git pull from post-receive hook.

Step 4: Give the executable permission to this post-receive hook
In this last step, just give executable permission to this post-receive file and you’re done
[sourcecode language=”shell”]
chmod +x /path/to/your/folder/myrepo.git/hooks/post-receive
[/sourcecode]

That’s mainly it 🙂 Now whenever you push your code from local machine to this remote git repository, your code will be deployed instantly.

I hope you’ve enjoyed this article and I would love to hear your comments.