Latest Updates: kohanaphp RSS

  • Articles

    KohanaPHP and Memcached

    Stii 3:56 pm on May 25, 2009 | Comments: 4 Permalink | Reply
    Tags: caching, database, kohanaphp, memcached, , optimization, sql

    Kohana PHPThis is shockingly simple… Almost so simple that I’m waiting for the problems, but after five days there has been none so far!

    When you develop a web application, at some point SQL query optimization just don’t cut it anymore. At Gatorpeeps, you will see we show each user’s latest blog post underneath each of his updates. The problem with this is that on any given page, we’ll run a query per update to get the user’s latest blog post. This is less than ideal, since it is repeating the same queries for every single visitor to a Gatorpeeps page.

    What we want to do is to cache the repetitive query for a certain amount of time, so that instead of querying the database, it fetches it from the cache, dramatically reducing database load and improving speed.

    With the Kohana PHP framework you have a number of options to your disposal namely:

    • File – File cache is fast and reliable, but requires many filesystem lookups.
    • SQlite – Database cache can be used to cache items remotely, but is slower.
    • Memcache – Memcache is very high performance, but prevents cache tags from being used.
    • APC – Alternative Php Cache
    • Eaccelerator
    • Xcache

    We opted for Memcached since it is fast, stable (so far at least!) and extremely simple to get going. We installed and configured it on our server (you should find lots of great guides for doing this if you search for it). We made sure the daemon is running then configured Kohana to use it. Very simple:

    Open the cache.php file located in the system/config directory. Change it to:

    $config['default'] = array
    (
    	'driver'   => 'memcache',
    	'params'   => '',
    	'lifetime' => 3600,
    	'requests' => 1000
    );
    

    If you run Memcached on the same server as your PHP site, you can skip ahead and implement it. If you run it on a different server, you need to change the cache_memcache.php file also located in system/config. If you have more than one memcached server, you can add them to the $config['servers'] array.

    $config['servers'] = array
    (
    	array
    	(
    		'host' => '127.0.0.1',
    		'port' => 11211,
    		'persistent' => FALSE,
    	)
    );
    
    /**
     * Enable cache data compression.
     */
    $config['compression'] = FALSE;
    

    In your source code, you can now use the cache. We have a static function in a helper method to fetch the latest blog post of a user. We get a cache instance and we check if the entry exists in the cache. If it does, we return the result otherwise we add it to the cache with a lifetime of 10 minutes.

    <?php
    ... truncated ...
    public static function getUserLatestBlogPost($user_id)
    {
        $cache = Cache::instance();
    
        // Get the latest blog post from the cache by looking for an unique id like latest_post_123
        $post = $cache->get('latest_post_' . $user_id);
        if ($post) {
            // Found an entry in the cache. Return it.
            return $post;
        } else {
            // There is nothing in the cache for this user, so we need to fetch it from the database and
            // add it to the cache.
            $newpost = self::sqlUserLatestBlogPost($user_id);
    
            // Add it to the cache, changing the default lifetime from 1 hour (3600 seconds) to 10 minutes (600 seconds)
            $cache->set('latest_post_' . $user_id, $newpost, NULL, 600);
            return $newpost;
        }
    }
    ... truncated ...
    

    That’s it. It is really that simple! :) Now, you would probably want to write a method that deletes an old entry if a new entry is inserted into the database and reload the new blog post into the cache.

    REMEMBER: Use caching wisely! It is great, but as they say, too much of a good thing is bad. First make sure your SQL queries are properly optimized before you cache it. Make sure the data you cache is okay to be cached. What I mean by that is it would be senseless to cache data that is very dynamic and changes often. Caching everything WILL have an undesirable effect ;)

     

    Welcome back! You should subscribe to my RSS feed here.
    You should follow me on Twitter here
    You should follow me on Gatorpeeps here.

     
  • Articles

    More reasons for Gatorpeeps

    Stii 1:54 pm on May 11, 2009 | Comments: 3 Permalink | Reply
    Tags: , , kohanaphp, microblogging

    Finally we can talk about Gatorpeeps officially! We’ve been rather quiet about it, primarily since we needed to finish a few things and stress test it before we punted it.

    gatorpeeps

    We had our fair share of “Blegh, another Twitter clone…” and we expected it. The thing is, we love twitter! Always have, always will.

    So why did we clone it then? Simple. Some of the reasons Justin already covered over here, but I’d like to add that Afrigator was in need of something social networky. We needed to add a communication dimension and as everybody knows, there is no better way to do that other than Twitter. Yes, we could have leveraged off the Twitter API. That is true, but the Twitter API is not without it’s limitations.

    Besides that, we also have a few other ideas, such as Twitter recently killed SMS functionality in Africa, and it left a huge gaping gap in that market.

    We did not leverage off some Open Source app like Laconi.ca or Jaiku. We wanted to initially, but due to the fact that we want to seamlessly integrate Gatorpeeps with Afrigator and add a bunch of unique features, we thought it best to rather develop our own flavor into the mix. For those interested, it is backed up by the brilliant Kohana PHP framework :). Was it the best idea? The right thing to do? Time will tell.

    Now the real work starts. Now we need to do all these promised features and integration… Fun times!

     
     
  • Articles

    Kohana PHP. One application, many domains?

    Stii 1:55 pm on January 7, 2009 | Comments: 4 Permalink | Reply
    Tags: , kohanaphp

    In Kohana PHP’s config file they have a bunch of weird settings that you have to specify. I cannot for the life of Brian understand why! :P

    I’m talking about this. The very first thing you need to set:

    <?php
    
    $config['site_domain'] = 'mysite.com';
    

    Now, I can understand the logic if you want to run your site off a directory in your domain like mysite.com/mysite, but still. Personally, I think, the URL should not be forced and it should rather just use $_SERVER['SERVER_NAME'] to determine the site domain. What they should ask is for a directory config item if you want to run your site off a directory on your domain:

    <?php
    //Leave blank if site is in the root directory
    $config['site_directory'] = 'mysite';
    

    Now lets suppose you want to do a mobile site. You should never have to replicate your code and maintain 2 code bases. You know. The DRY principles? I want to run two domains off the same code base, but make my decision in the code whether I want to display default site templates or whether I must display the mobile templates. (See: Overriding default template in Kohana PHP if you’re unsure what I’m on about). For example: I have my normal site running on http://mysite.com and I want my mobile site to live at http://mysite.mobi. The difference between the two are the templates. I want to use the rest of the codebase as is since they’re all the same for both sites.

    The solution is pretty much straight forward. All you need to do is:

    <?php
    
    $config['site_domain'] = $_SERVER['SERVER_NAME'];
    

    or (if your application lives in a directory)

    <?php
    
    $config['site_domain'] = $_SERVER['SERVER_NAME'] . '/mysite';
    

    and viola! It works like a charm. But it is still very unnecessary! That’s my beef about it. This is one of those weird things that spilled over from Code Igniter. Maybe this could change at some stage? Maybe I’m missing something and in fact it is quite critical that you do specify it like they prefer? Hope someone could clarify. It is quite possible that I’m missing something very obvious… I’m known for that from time to time!

    UPDATE… Sigh

    It turns out that if you leave $config['site_domain'] blank, it defaults to using $_SERVER['SERVER_NAME'].

    <?php
    
    $config['site_domain'] = '';
    

    At least, now I know!

    Also, read Darb’s comment below on why you’d want to enforce a single domain. Makes sense!

     
     
  • Articles

    Overriding default template in Kohana PHP

    Stii 4:57 pm on January 6, 2009 | Comments: 4 Permalink | Reply
    Tags: kohanaphp, template_controller

    If you use the template controller in Kohana PHP you may need to override the default template you specified at some stage. This is extremely easy, but it is not documented anywhere, so I thought it might be a good idea to show you.

    Normally you would specify the default template like this:

    <?php
    class Home_Controller extends Template_Controller
    {
        public $template = 'my_template';
        ...
    }
    

    Now lets suppose you are developing a mobile version of your site and you would like to use a different template for whatever reason. In your index() function you would have something like this:

    <?php
    class Home_Controller extends Template_Controller
    {
        public $template = 'my_template';
        ...
        public function index()
        {
            if ($is_mobile) {
                //Use a different mobile template
                $this->template = new View("mobile_template");
                ...
            } else {
                //Do the normal thing and let it
                //auto generate the page and use my_template
                ...
            }
        }
    }
    

    In effect, all you need to do is to override your default specified “my_template” by assigning a new View object which would be a different template that does what you need it to do.

    Another way of doing it is as follows:

    <?php
    class Home_Controller extends Template_Controller
    {
        public $template = 'my_template';
    
        public function __construct()
        {
            if ($is_mobile) {
                $this->template = 'mobile_template';
            }
            parent::__construct();
        }
    ...
    }
    

    Assign your new template to the variable in your controller’s constructor before you call the parent class (Template_Controller) constructor. The Template_Controller does the following in it’s constructor, FYI:

    $this->template = new View($this->template);
    

    If you do the following, it would #FAIL:

    <?php
    class Home_Controller extends Template_Controller
    {
        public $template = 'my_template';
    
        public function __construct()
        {
            parent::__construct();
            if ($is_mobile) {
                $this->template = 'mobile_template';
            }
        }
    ...
    }
    

    If its not obvious to you, what happens is that in the Template_Controller constructor it assigns the my_template View object to the $this->template variable and if you assign ‘mobile_template’ to it after the Template_Controller constructor was called, you effectively override $this->template with a string called ‘mobile_template’. Very effectively… ;-)

    There! I hope this helps someone somewhere.

     
     
  • Articles

    Kohana PHP Framework

    Stii 4:09 pm on January 5, 2009 | Comments: 6 Permalink | Reply
    Tags: , kohanaphp, mvc

    Now I’m not going to start a “my-framework-is-better-than-yours” pissing contest again. I’ve learned that 1) People are not easily convinced that what they are using is actually inferior to what they should be using and 2) life is simply too short to try and convince people otherwise.

    picture-24

    No, I will say that Kohana PHP is MY framework of choice. I like the way it utilize strict PHP5 OOP practices. It is very similar to Code Igniter and I’ve been a fan of CI for a long, long time. In fact, it was based on CI. I like the flexibility. I like the way templates and views work. I like the way it uses convention over configuration or as they call it “a cascading filesystem“. I like the fact that it allows you to access the $_GET variables which CI does not by default. I can go on and on and on. There are many. The list is too bloody long.

    The community is smallish, but it is growing. It is completely Open Source and is not controlled or maintained by a single entity as is the case with CI.

    All in all, it fits me. It allows me to do what I need to do quickly. I know it might not be perfect, but that does not matter as long as it gets my work done.

    Word of advice: If you are looking for a neat/fast/flexible little framework in PHP, check it out. I highly recommend it! :)

    Oh, and FYI, both Afrigator and (I believe) Ushahidi are proudly Kohana PHP Powered!

     
     

About Me

Software developer at Afrigator.com Love Python, do PHP.
c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
esc
cancel