How to Use Third Party Autoloaders in Yii

Standard

Using third party libraries in Yii is super easy. Just put the library, e.g. Google, under vendors directory and add the following lines at the beginning in your controller where you wish to use it.

Alternatively, you can include the first line mentioned above in your Yii application’s main.php imports section as shown below (line 4).

And then include the desired file in your controller (2nd line) before using it. That’s all.

However, you might run into issues if you are integrating a third party library with it’s own autoloader. Yii’s guide has some documentation on how to tackle the situation but it doesn’t work out of the box for most of the people. The reason why integrating third party libraries with autoloaders in Yii isn’t as simple as integrating a non-autoloader library is that third party autoloaders conflict with Yii’s own autoloader.

In such a situation, you can use the code mentioned below and change the path/library as per your requirements in second line. You can use it anywhere in your code (most likely in controller) as needed.

Trick here is to temporarily unregister Yii’s autoload functionality before adding third party autoloader and then re-enabling Yii’s autoloader. You still need to include the vendors directory in your application’s main.php as shown in second code snippet above.

I am not sure if this works in Yii 2 as well, most likely it won’t since Yii 2 is a complete rewrite, but this certainly works in Yii 1.x releases.

Tentative delivery date calculation in PHP

Standard

Here is a simple function you can use if you need your PHP application to display a tentative delivery/completion date to your customer. It excludes the weekends in calculation so only business days are considered. For example, if your e-commerce site ships a product in three business days and customer orders on Thursday then this function will return tentative delivery day as Tuesday, not Sunday. Continue reading

Active menu highlighting in Yii views or layout

Standard

One of the most common thing one need to do while developing a website is to highlight the currently selected menu item in main navigation. Essentially what you need to do is to check if the current URL and link to a given menu is same. If they match then we need to apply a CSS class to given menu so it’s shown differently from other menu items.

Below is how you can do it in Yii framework. I have created a small function below which checks the current URL and the URL of menu. If they match then it returns true else it returns false.

I usually create a utility class in which I include all utility functions like this one. I place this class under components and use it across the project. Now this is what the above mentioned function does.

  1. It first checks if the URL is of a static page or of a standard controller action.
  2. If it’s not for a static page then it compares the current controller and action with the passed controller and action. If they match then it returns true to the calling view/layout to notify this menu need to be highlighted. If not, it returns false.
  3. If page is also passed as an argument then it means it’s for a static page. In this case we also compare another URL parameter ‘view’ along with controller and action to ensure we are highlighting the correct page menu.

This function won’t work in itself since it need support from view/layout when our menu is. Below is sample code for how it should be used.

Here I have create three menu items. First is the ‘Home’ menu which links to site’s index page. Second is a link to static page called ‘faq’ and third is a link to post details. This function has limitations like it currently checks only for controller and action and does not consider if there are more URL arguments depending on which menu may be different. However it should give you a fair idea of how active menu highlighting works in Yii and it’s not difficult to extend it to make it work for more complex URLs. Enjoy!

How to use Twitter Oauth API inside your Yii application

Standard

Let’s face it. Twitter API is one of those API’s you can’t simply afford to neglect if the application you are developing has any social elements. You can almost do anything using Twitter API which you can do when you are logged in to Twitter site as a user which make it incredibly powerful API.

There are hundreds of tutorials out there which will help you in integrating Twitter API into your PHP web applications. This post is specifically for integrating Twitter OAuth API in Yii framework (my latest favorite) based web application though you should be able to use the same steps with slight modifications for any other PHP framework or even in core PHP applications.

In this tutorial, we’ll use a simple Yii based blog application from Yii tutorial (http://www.yiiframework.com/doc/blog/) to integrate Twitter API in it. As an example, I’ll be showing how you can auto tweet each blog post to your Twitter account when a new post is created. The library we’ll be integrating in Yii application is quite comprehensive so you’ll be able to use the same setup for any twitter API call/function, not just auto tweeting of posts.

Step One: Setting up twitter app

  • Hop on to https://dev.twitter.com/
  • Login using same twitter account which you wish to integrate in site, e.g. twitter account on which you wish to auto tweet each blog post.
  • Click on “Create an app” link – https://dev.twitter.com/apps/new
  • Follow the steps like give a name to application, description of application, URL of the site where you would be using the API integration. If you are developing the application locally on your system (PC, Mac, *nix), you should be able to use localhost (though I haven’t tried it but it works on most of other API’s like Facebook).
  • Leave the callback URL field empty for now. Below is how it would look like once you have provided all required details.

How to setup Twitter Oauth App

  • Accept the terms, provide captcha value and click on “Create your Twitter Application” button.
  • If everything goes fine, you’ll be taken to application details page. From where, click on “Settings” tab.
  • Change the application type as “Read and Write” (default is Read Only). You can also upload image for your application. Save the settings by clicking “Update this Twitter applications’s settings” button.

Set app type to read and write

  • Go back to details tab and scroll to the bottom of the page where you’ll find “Create my access token” button. Click on that, it’ll generate access tokens for your application.
  • We’re almost done here. Now, go to “OAuth tool” tab and take a note of Consumer Key, Consumer Secret, Access Token and Access Token Secret. Of source, values won’t be empty as below 🙂

Oauth settings

Step 2: Setting up Yii application

  • Go to https://github.com/themattharris/tmhOAuth and download. Why this and not any other library? Well, I couldn’t find any other library which is as well documented as this one and is complete in terms of all supported API calls. In fact, this is one of the top 5 libraries recommended by Twitter itself for PHP.
  • Extract the downloaded file and copy the extracted folder under /protected/vendors folder in your Yii application. Rename the folder name to anything you like. For this example, we rename it to tmhOAuth.
  • Edit /protected/config/main.php and import the files we just added by modifying the import setting.

  • We are done with the Yii setup. Now the only thing pending is to actually auto tweet the post when it’s created and saved in database. Let’s move on to step 3.

Step 3: Making it all work

Now let’s go back to the example Yii blog application tutorial to figure out which is the best place to auto tweet the story. You can do it in controller or model but I would recommend doing it in model in afterSave() callback of Yii model class.

  • Import the required twitter library files in post model class as mentioned below.
  • Instantiate an object of tmhOAuth class by passing consumer key, consumer secret, access token and access token secret as arguments. Remember, we took a note of these values at the end of step one.
  • Make API call for tweeting the post and check the status of call whether it was successful or failed.

Once you have done this, try making a blog post and it should appear on your twitter account in the format we created as soon as you create it. Now there are many optimizations you can do in the function above. For example, you may want to check for length of title and truncate it in such a way that words are not truncated in between by substr function or you may want to retry posting to twitter in case the first call fails. However the posts is getting too long so I leave that part for your to future out 🙂

This is a small example of what you can do with the API, now your Yii application is equipped with full Twitter power and you can make use of any API call in your Yii application. To make things simpler, Matt Harris (Author of the twitter lib) has provided examples for each API call which you can simply copy paste in your application and adjust as needed. Here you go  – https://github.com/themattharris/tmhOAuth-examples

I hope you find this tutorial helpful. Enjoy!