Howto Setup Vim IDE for PHP Development

As a PHP developer one has quiet a lot of choices of IDE. Some are graphical will built-in features like debugging, code completion, auto indentation, syntax highlighting, code checking and many more. But those IDEs are very heavy and slow to use, and I know many people like me who just can’t live without Vim and want to use Vim for all type of text editing they do, whether they are writing code, editing configuration files or may be creating simple text files.

Recently I posted a screenshot of my Vim editor and got a lot of emails that how did I setup Vim that way. So, I hope this howto will be easy enough for everyone to follow and setup their Vim as their PHP  IDE. For the sake of simplicity I am assuming you are using Vim on Linux or Linux like system. If you are a windows user then this guide should still work for you, but I might not be able to provide Windows related details where needed.

Features that we will add or enable in Vim to make it a complete IDE.

  • Code Completion
  • Tag Lists
  • Project Management
  • Syntax Highlighting
  • Code Checking

First we need to download following Vim scripts and extract them in our ~/.vim directory.

Download above scripts one by one and install them. Installing them is easy just unzip them in you .vim directory which is located in your home directory. Now we need to download few files in our .vim/plugin directory. Download the following Vim scripts directly into your .vim/plugin directory.

 

Now that you have installed above scripts, you are almost all set to go. You just need to paste the following content in your .vimrc file which is located in your home directory.

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" ~/.vimrc                                                      "
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"                                                               "
" Version: 0.1                                                  "
"                                                               "
"                                                               "
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
 
" Hightlight the ifs and buts
syntax on
 
" Plugins and indentation based on the file type
filetype plugin indent on
 
 
" Don't remember source of this, i think it was already in my .vimrc
" Tell vim to remember certain things when we exit
"  '10 : marks will be remembered for up to 10 previously edited files
"  "100 : will save up to 100 lines for each register
"  :5000 : up to 5000 lines of command-line history will be remembered
"  % : saves and restores the buffer list
"  n... : where to save the viminfo files
set viminfo='10,\"100,:5000,%,n~/.viminfo
 
" omnicomplete from: http://vim.wikia.com/wiki/VimTip1386
set completeopt=longest,menuone
inoremap <expr> <CR> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
inoremap <expr> <C-n> pumvisible() ? '<C-n>' :
  \ '<C-n><C-r>=pumvisible() ? "\<lt>Down>" : ""<CR>'
 
 
"###########################
"##       PHP             ##
"###########################
" The php doc plugin
" source ~/.vim/php-doc.vim
inoremap <C-P> <ESC>:call PhpDocSingle()<CR>i
nnoremap <C-P> :call PhpDocSingle()<CR>
vnoremap <C-P> :call PhpDocRange()<CR>
 
" run file with PHP CLI (CTRL-M)
:autocmd FileType php noremap <C-M> :w!<CR>:!/usr/bin/php %<CR>
 
" PHP parser check (CTRL-L)
:autocmd FileType php noremap <C-L> :!/usr/bin/php -l %<CR>
 
" Do use the currently active spell checking for completion though!
" (I love this feature :-)
set complete+=kspell
 
" disable tabs
set expandtab
set shiftwidth=4
set softtabstop=4
 
" highlt matches
set hlsearch
 
" Taken from http://peterodding.com/code/vim/profile/vimrc
" Make Vim open and close folded text as needed because I can't be bothered to
" do so myself and wouldn't use text folding at all if it wasn't automatic.
set foldmethod=marker foldopen=all,insert foldclose=all
 
" Enable enhanced command line completion.
set wildmenu wildmode=list:full
 
" Ignore these filenames during enhanced command line completion.
set wildignore+=*.aux,*.out,*.toc " LaTeX intermediate files
set wildignore+=*.jpg,*.bmp,*.gif " binary images
set wildignore+=*.luac " Lua byte code
set wildignore+=*.o,*.obj,*.exe,*.dll,*.manifest " compiled object files
set wildignore+=*.pyc " Python byte code
set wildignore+=*.spl " compiled spelling word lists
set wildignore+=*.sw? " Vim swap files
 
 
" Enable completion dictionaries for PHP buffers.
autocmd FileType php set complete+=k~/.vim/dict/PHP.dict
 
" PHP Autocomplete
autocmd FileType php set omnifunc=phpcomplete#CompletePHP
set ofu=syntaxcomplete#Complete
 
" You might also find this useful
" PHP Generated Code Highlights (HTML & SQL)                                              
let php_sql_query=1
let php_htmlInStrings=1
let g:php_folding=2
set foldmethod=syntax
 
" --------------------
" Project
" --------------------
map <A-S-p> :Project<CR>
map <A-S-o> :Project<CR>:redraw<CR>/
nmap <silent> <F3> <Plug>ToggleProject
"let g:proj_window_width = 30
"let g:proj_window_increment = 150
 
nnoremap <silent> <F8> :TlistToggle<CR>
let Tlist_Exit_OnlyWindow = 1     " exit if taglist is last window open
let Tlist_Show_One_File = 1       " Only show tags for current buffer
let Tlist_Enable_Fold_Column = 0  " no fold column (only showing one file)
let tlist_sql_settings = 'sql;P:package;t:table'
let tlist_ant_settings = 'ant;p:Project;r:Property;t:Target'
 
" auto change directory from: http://vim.wikia.com/wiki/Set_working_directory_to_the_current_file
autocmd BufEnter * if expand("%:p:h") !~ '^/tmp' | lcd %:p:h | endif
 
" when we reload, tell vim to restore the cursor to the saved position
augroup JumpCursorOnEdit
 au!
 autocmd BufReadPost *
 \ if expand("<afile>:p:h") !=? $TEMP |
 \ if line("'\"") > 1 && line("'\"") <= line("$") |
 \ let JumpCursorOnEdit_foo = line("'\"") |
 \ let b:doopenfold = 1 |
 \ if (foldlevel(JumpCursorOnEdit_foo) > foldlevel(JumpCursorOnEdit_foo - 1)) |
 \ let JumpCursorOnEdit_foo = JumpCursorOnEdit_foo - 1 |
 \ let b:doopenfold = 2 |
 \ endif |
 \ exe JumpCursorOnEdit_foo |
 \ endif |
 \ endif
 " Need to postpone using "zv" until after reading the modelines.
 autocmd BufWinEnter *
 \ if exists("b:doopenfold") |
 \ exe "normal zv" |
 \ if(b:doopenfold > 1) |
 \ exe "+".1 |
 \ endif |
 \ unlet b:doopenfold |
 \ endif
augroup END
 
" PHP code sniffer
" If code sniffer is installed you can run it on current php file by running 
" :Phpcs
function! RunPhpcs()
    let l:filename=@%
    let l:phpcs_output=system('phpcs --report=csv --standard=YMC '.l:filename)
"    echo l:phpcs_output
    let l:phpcs_list=split(l:phpcs_output, "\n")
    unlet l:phpcs_list[0]
    cexpr l:phpcs_list
    cwindow
endfunction
 
set errorformat+=\"%f\"\\,%l\\,%c\\,%t%*[a-zA-Z]\\,\"%m\"
command! Phpcs execute RunPhpcs()

Thats it, now you are all set to go. Following are the few quick commands to get you started to use all the features you have just enabled in your Vim IDE.

F3: To start using project manager.
\C: After starting project manager this key combination will allow you to add new project.
F8: Tag list window
Ctrl+L: To run the syntax checking on your php file
Ctrl+P: On any class/function definition to add php doc strings
“:PhpCs”: To run PHP Code sniffer on your php script. (this requires code sniffer to be installed).
Ctrl+n: On any word to use Auto completion feature of PHP.

I will soon write another howto to explain how can you use further features of your IDE. You should subscribe to the feed or follow me on twitter to stay updated. 🙂

Vim as PHP IDE

If you think Vim is just another text editor then think again. Vim is not a text editor, neither its an IDE, its everything.

Here is just a small screenshot of Vim on my machine being used as IDE for the PHP project, a howto and other details will soon be up on this blog as soon as I finish the project.

Vim PHP IDE
Vim as PHP IDE

UPDATE: I have wrote “How to Setup Vim IDE for PHP Development“.

You might want to follow me on twitter or subscribe to RSS Feed to get future updates on the topic.

How to get Twitter follower count in PHP

Are you are WordPress developer and want to show twitter follower count on your wordpress blog or you want to show your Twitter follower count on your PHP based site? You might be wondering how to get that number from twitter. So here is the code snippet with details so you can write your own or you can just copy paste this one.

The new Twitter API allows you to read user information in XML and JSON format, so all you have to do is get the information in XML format and read the value between <followers_count> element.

Here is the code snippet for reading twitter followers count in PHP.

<?php
 
$username = "hameedullah";    // Set this to username whose follower count you want to read.
 
$twitter_api_url = "http://api.twitter.com/1/users/show.xml?screen_name=$username";
 
$api = curl_init($twitter_api_url);
curl_setopt($api, CURLOPT_HEADER, 0);
curl_setopt($api, CURLOPT_RETURNTRANSFER, 1);
$xml = curl_exec($api);
curl_close($api);
 
if (preg_match('/followers_count>(.*)</',$xml,$match)!=0) {
    $followers_count = $match[1];
}
 
echo $followers_count;
?>

If you have any issues with the code snippet let me know in comments, or if you are looking for a code to get something else from the Twitter API let me know in comments too.

How to exclude a category from your main wordpress index and RSS feed

Few days ago I was experimenting with Twitter tools, so I found that the Tweet Digest posts created by Twitter tools are being listed with my other posts in the main index of my blog. Twitter digests posts were not looking good to me as the Twitter digests posts from Twitter Tools were long and they were making my other posts unfindable. So I excluded that Category in the main index listing of my blog. But just yesterday I added my blog to FriendFeed and this is when I figured out that I should also be disabling the ‘Twitter Archive‘ category in the RSS feed of my blog. So I did some research and found very helpful trick from wpbeginner. Below I will show you how I used the code from wpbegginer not by just copy-pasting it but by tweaking to fit my need. Before you read further let me just remind you what I am trying to do here. I am trying to disable ‘Twitter Archive’ category (with category id 27) in the main blog listing as well as in my default RSS feed. So to simply exclude the Category from RSS feed as mentioned on wpbeginner I had to include the following code in my theme’s functions.php.

function catExclude($query) {
    if ($query->is_feed) {
         $query->set('cat','-27'); //Don't forget to change the category ID
    }
    return $query;
}
add_filter('pre_get_posts','catExclude');

But the above code proved to be not working for my case, as I wanted to exclude the category without breaking customized feed or category based feeds of my blog. As the above code is explicitly setting category with category ID ’27’ to be excluded, it doesn’t matter if you use the customize feed URL to exclude other categories. In simple words the above filter does not preserve the values of cat in the query string, it just sets the new value regardless what was provided in the url to get the customized feed. So I just can’t use this function, being a perfectionist I don’t like breaking things to build or do something new. So I did some more research on the above code and found that I can do play with $query object that is being passed to catExclude function above.

After reading about the $query object of class WP_Query I found that there is a function which allows to get the value of current variable in query string. So I just added an if condition to the above code to check if there is already a value set for ‘cat’ in query string, if there is already a value set then I don’t modify the value, else I just exclude my ‘Twitter Archive’ category. By using this check of an existing cat value I successfully excluded ‘Twitter Archive’ category form default RSS feed with out breaking the functionality and I can still have separate feeds for all my categories. Not only that but my ‘Twitter Archive’ category can also have its own dedicated feed without showing up in main default RSS feed. Below is the final code that I used to exclude the ‘Twitter Archive’ category from my RSS feed.

function catExclude($query) {
    if ($query->is_feed) {
       if (!$query->get('cat'))  {
            $query->set('cat','-27'); //Don't forget to change the category ID
       }
    }
    return $query;
}
add_filter('pre_get_posts','catExclude');

Now there is one last thing I modified in the above code to use it to exclude category in the main index of my wordpress blog. As I mentioned earlier about my previous post on the topic, that describes another way of achieving the same thing. But in case you don’t want to use that method and want to keep your edits to the single file and exclude your selected categories from both the main index and RSS feed then you use the below code.

function catExclude($query) {
    if ($query->is_feed || $query->is_home) {
       if (!$query->get('cat'))  {
            $query->set('cat','-27'); //Don't forget to change the category ID
       }
    }
    return $query;
}
add_filter('pre_get_posts','catExclude');

I hope you already have noticed the use of is_home in if condition. If you will use the code above with is_home condition then you don’t need to use the method that I mentioned in my previous post about excluding category in main index of wordpress blog. Now the last thing you might want to do with the above code that is to exclude multiple categories. Specify the multiple categories as below in your $query->set call.

$query->set('cat','-27,-30,-32');

I know the above code samples might not make much sense to non PHP programmers, so if you need to edit your wordpress blog and does not know how, you can hire me. You can also find my contact information on the contact page.

If you know a better way of doing the same thing, kindly share with us in the comments. Even if you don’t know a better way, let me know in comments what do you think about this trick and if you like it then don’t forget to share it with your friends.

How to exclude posts of a single category from main listing of your wordpress blog.

As I recently launched this blog I am still trying to experiment with few things, so I enabled Daily and Weekly digests of my tweests in Twitter Tools. Now I still want to have those digests but I don’t like seeing the posts in the main post listing or in feeds. So I decided to hack into wordpress and exclude the “Tweets Archive” category from the main post listing. I had to do bit of research into WordPress Codex and some testing to make it working so I decided to share it here on the blog as well.

  1. Goto your Blog Admin and then goto Categories under Posts.
  2. Click on the Category you want to exclude and then note the Category ID number. You can see the number in the picture below that is shown at the end of the URL in the address below. In my case it was category id 27 which I had to exclude.
  3. How to find the Category ID on your wordpress blog

  4. Goto your WordPress Blog Admin and then goto Editor under Appearance.
  5. Wordpress Blog Admin Appearance Theme Editor

  6. Open the file “index.php” from right column and find the line “<?php if (have_posts()) : ?>”
  7. Wordpress Blog Theme Editor index.php file

  8. Just before that line add following code:
  9. <?php if (is_home()) { query_posts($query_string . "cat=-27"); } ?>

  10. Save the file and you are done.

Congratulations if you have followed till here. This might not be your first WordPress hack or you might have already done the same thing probably using some other method or may be plugin, or you might have learned something new in this short hackorial. Let me know you thoughts or give me some suggestions, I would love to hear from you.