Saturday, May 29, 2010

Why you should Twitter ?

It’s been a year since i joined Twitter. Tweeting what i found useful out there surfing, thinking that might interest some one else out there too and tweeting my days as i am living.

First day at twitter was hell. No idea about the interface. Most interesting,  sharing something would be called tweeting! I wondered, what the heck this tweet thing is?? Slowly i began to understand how tweet chirps & why it rocks!


stat

Okay after a year now, i admit i am addicted to twitter now, a day without tweet?? Ahh something is missing. lol. i decided to write why i find twitter useful. It might help someone starting out with twitter.

This is how the idea about this post came in mind:

planning

I’ll be posting one tweet a day chaining them to each other in reverse order from 10 to 1.


Click the link below to go through all the 10 tweets

Why you should twitter?

I started writing this blog post back in May 29th. Its June 14th today, 15 days, 10 chained tweets & this post, i am happy that finally completed this share. My idea about this post was, i wanted to share why twitter as a service is a good place to hang out and give a try. These are solely my view about the service and any views from your side is highly welcomed. Please bear with the length of the post, i couldn’t make it short!

1st tweet:

1

Take it as a web SMS with everyone with their unique identity @username. If you want to talk with someone, just send a tweet to them addressing their username adding @ prefix to it, and there you done. The first thing i found interesting when i started with twitter was its username thing, your contact address is now: @yourusername why bother with those trailing domain names like gmail.com or live.com ??
The simplest of all, you will have a @username that’ll represent you as a person throughout the globe.

Twitter is a bit confusing at first. But few really understand the fun being in it and get attached. Most of them take it hard to grasp and from the first day or two, stop thinking about twitter. If you left just creating your twitter account you are the one who know it well :) But here i am trying to share with you actually what people say good about twitter.

The idea behind twitter is to allow people express their thoughts in 140 characters. Does that counts? Does such small piece of information have any value?? Think about every people in the world tweeting and sharing about things around them in 140 characters, this produces the content enough to read throughout your life. And it’s by far the human nature to pass the meaningful information to others, which is what twitter expressions get higher values. More ever, value of such expressions will come out more profound when that information is processed or presented in a meaningful way The Twitter Trends, that are build around the highest talked topics in twitter are one of the examples of such extraction. And where else in the cloud you’d find such a highly user filtered content??

Twitter facilitates social networking, but it's not a social networking website. In fact, the way Twitter works is quite different from social networks: when you accept friend requests on social networks, it usually means you appear in that person's network and they appear in yours. Following on Twitter is different, because instead of indicating a mutual relationship, following is a one-way action that means you want to receive information, in the form of tweets, from someone. Twitter allows people to opt-in to (or opt-out of) receiving a person's updates without requiring mutual following.
from support entries : Twitter

Actually, twitter is not a Social Network. Twitter themselves don’t call it a social network, it is one of the largest site in web with enough userbase to keep it stand out among other web services. It’s actually a Microblogging Service. Call it anything you like, this a place where people gather, share & talk about things that matters to them and their life. There are endless possibilities with such group of people. You can call it a social network, a news media or a information broadcast service. Say it a place where you keep up with your and your friend’s day to day life. Call it a place to hang out with new people around the world or call it a place to share what you like. If you are a marketer or in business, take it as business tool and start tracking you customer re-views. If you own a blog or some online business, there’s no other service like twitter to get some specific visitors. You are a university student doing some data analysis, there’s no other service as lively as twitter to refer. You are a musician, want to get in touch with your fans, take it as a place to meet with your fans. Give it any use you want. But answer to this question: How do you use your mobile ??? to SMS ?? to call friends? okay fine, it’s completely up to you to use the mobile service, for anything or any purpose you want,  what i am talking here is, exactly, twitter is a way, a tool, the world is using Twitter to SMS 140 characters to others. Give it any direction you like, give it a name you like, use it wherever you need.

2nd tweet:

2

Out of the millions of tweets from different geo locations, different cultures and variety of people twitter is trying to extract some really breaking topics as trends. You being in twitter, actually will be contributing to the information from your locality. We can build twitter application on the top of twitter APIs and build our own online community around our shares. This will be representing our views in the world wide web.

Join twitter today and start tweeting - what ever happening around you, what you find interesting and what matters to you. Start following some people. Get interactive. Be polite, learn about the conversation etiquettes/twitter etiquettes. Slowly you’ll begin to realize you are actually sharing your day to day life in twitter. The good part is everyone is doing the same.

3rd tweet:

image

Twitter is increasing in its userbase day per day. People will finally land up in twitter i am sure on this. The simple interface, with new experience. Despite being such a large web service, twitter provides a very simple one step privacy feature. If you like to go private with you twitter profile, simply goto: Settings –> and mark your profile as private & save it. Done!

privacy block

Most of the time, this one simple privacy tick will suffice your privacy requirement. If you find some of people you follow or those following you annoying simply visit their profile and block them or report as spam.  I loved twitter for this simplicity in privacy setting.

list

Twitter list are great in the sense, they show all the latest tweets from the people in the list. Create a twitter list & think about your live office meeting :) really great! The most interesting is the privacy feature of the list. Please, read the note in the snap above.

 

4th tweet:

4

You may think tweeting would be useless, unless you are a brand using twitter for business, a celebrity or someone with higher number of followers, this ain’t need to be so. Behind every twitter name, there’s a face, like yours, and who knows that face might have same interest as you have. Every tweet/piece of information is equally exposed, sharable and holds certain human value. Each tweet shares an equal chance to be a trend or a master piece of information.

What do you think can be shared in 140 characters? A blog? or a story? or what? an announcement?? The concise nature of tweet itself demands some higher degree of insightful, useful & interesting 140 character inside it to be sharable and build interest in people in your network or to a completely stranger. But don’t hold an urge to be interesting, informative, it’s your lifestream – be you and tweet your thing! That is what becomes your brand in twitter. This will lead you to a circle of people around you who hold similar taste of life.

5th tweet:

5

The timestamp below each tweet ( like …..few seconds ago) speaks about the Real Time nature of twitter. The real time here would mean – as it happens! Yeah, twitter is a stream of shared thoughts around the globe as they are happening right now. 

As i am writing this post now: The Apple Worldwide Developers Conference (WWDC) is going on. If we searched twitter for the WWDC keynote, it would show all the stream of tweets related to the conference. Yup, getting in touch with like minded people in real time was never this easy. You may like to watch: Twitter Search or Google Trends about the WWDC. Look at the Google search, you’ll see all the real time content is fetched from twitter. Even Google failed to beat Twitter’s real-time nature.

For quick glimpse of real time tweets let’s search for Google itself in Twitter & Google Trends. We will see hundreds of tweets coming per second on the topic.

Like these, getting info about any event, any topic of interest & meeting people who share the same interest is easier in twitter. Whether it was about Haiti or whether about the Google OS launch. The tweets were conveying the real time messages everywhere. Millions of people around the world were helping, fund raising for the support in Haiti with twitter. Peoples were arguing about the promises made by Google on the launch of Chrome OS. One reason, i want to live tweeting is this Right Here, Right Now thing.

Some other places to search for twitter content : Bing, Monitor (monitor let’s you search about three topics of interest at once & keep up with them, try using it)  Twazzup, Scoopler. All these services exists but i am happy with the search in twitter itself: http://search.twitter.com. Below, here are some sample search that you might enjoy. Before doing a search a search in twitter, i recommend you look at the Twitter Search Operators. These operators will help you filter your search to more useful tweets.

Twitter Search Examples:

Searching for movie this weekend?? Here’s a quick twitter search from the examples at twitter that will search tweets containing the word "movie", but not "scary", and with a positive attitude -  movie -scary :)

If you live around Kathmandu and want to find what people around are tweeting search near:kathmandu

Twitter users, use hash tags (#) anything with a # prefix, searching for a Job?? try searching for #job or job

You may wonder, what people mention @billgates, try this: to:billgates (this search might look scary at first, what the heck?? can people see my conversations?? but this applies to all the public profiles in twitter. Twitter conversations are public, If you like more privacy send direct messages or go fully private with your twitter profile. )

Want to listen a song, any random song?? okay songs are mostly shared with hastags like #np #nowplaying #listening #song etc.

Let’s filter them so that we’d only see tweets send from Blip.fm "listening to" source:blip.fm
Let’s broaden the search for something to watch or listen to  "listening to" OR now playing OR #np OR #nowplaying filter:links

FIFA, World cup 2010 is going to be fun with twitter:  #worldcup or #wc2010

There are endless possibilities using the twitter search & operators. And most of all, to get all this information from twitter you don’t even need a twitter account. Twitter search is public & can be accessed without setting up your account. Just land to the twitter home page start using the search.

Okay this was about how you’d get what information you want from twitter, but in the run, if you go on tweeting you too will be contributing to this open and real time place. So why don’t give a try now??

6th tweet:

6

You may wonder why 140 character limit?? Here’s what twitter have to say about the 140 limit:

SMS (i.e., texting on your phone) limits each message to 160 characters. Twitter takes that limit and reserves 20 characters for your username, leaving you 140 characters to play with. That’s how it started and we’ve stuck with it!
Taken from Twitter101 for Business  –  from Twitter 

140 is by no mean a limit. Twitter is ambitious to make it possible to allow people tweet from every possible device connected to the web, from your latest Android or from an oldest handset in the drawer. The limits in the character allows this to be possible, older devices do not support lengthy texting & twitter is about texting in Web.

There are sites available to attach your now playing lists (Blip.fm), your birthday celebration pictures (Twitpic), your important contribution announcements to the web or shorten the links you are sharing (Ping.fm, Goo.gl, Bit.ly etc). There are enough services available to share stuffs in twitter. With these free services, you’ll shorten the links & simply copy paste or auto share them in your tweets. There you go without crossing the limit.

The popularity of tweet has led the web to focus more on content rather then length. All popular sites like Google, Youtube, Flickr, every blog in the planet, now support url shortening to facilitate sharing on twitter to save some space to add your thought.140

I suggest you review your tweet once after writing it, give it some time, make it sharable, readable & interesting. This will increase you writing skills, your concentration skill & most of all you’ll learn to be economical – you’ll learn to value each space that’s left on the top right corner of the tweet box. Being content full with each tweet adds value to your profile too.

So will you get shrunk by these 140 characters micro blogging service?
There can be a limit on the number of characters you can tweet but not on the value of your thoughts that you attach to them!

7th tweet:

7

As far as my experience with Twitter says, twitter has never advertised anything or suggested any profile to follow. I like following back, i follow who follow me. In the scene, where every person in the world is tweeting & the service provider, Twitter Inc,  never used any any algorithm to target me as a business source for them, i am happy for their service. Join twitter and enjoy the add free platform. Follow people who interest you, enjoying being in the open sharing environment. I don’t want to argue here about twitter competitors like facebook, foursquare etc. who try to connect people with their algorithms & target personals for their benefit. But i enjoy the freedom in tweeting.

I see three types of personalities in twitter,

1. Person who enjoy their immediate niche. Enjoy following their closest circle & following their tweets. Including celebrities.
2. People who follow back for following them [ i am in this list ;) ]
3. Twitter Bots or Applications. Own twitter profile for business motives.

When you go through the profile of these three genres of twitter users you’d easily identify their category, by looking at their profile. Twitter bot are easily identified by looking at the source they tweet from that is : API. The point here is, you should  find which category you fall in? What’s the idea behind your twitter use??  

I tried many twitter apps to organize my twitter life. I used, tweetdeck, sysmic, ping etc but Twitter Web is enough for me. Their List service is enough to keep up with my nearest friends. Thanks Twitter for the add free environment. And i always argued, sometimes emotions are more important than algorithms! This applies 100% to twitter. It respects your choice, no suggestions, no advertisements and you follow people or be friends with them by choice, not because an algorithm behind their web server is monitoring your activity. 

 

8th tweet:

8

Twitter’s is a real time stream of data, 140 characters long, each with a meaning to certain person or community or nations.

According to TweeSpeed  there come around 35K tweets per minute. If you want to see the numbers of tweets increasing in real time look at the GigaTweet Application .

tweets per minutes

Twitter philosophy regarding the twitter use is they want people to be able to tweet from every device in the world. So, where does that data goes?? Is their any use of them?

Twitter has provided excellent APIs. These APIs are used to access the twitter data in real time. With these APIs People are building very useful application each minute, giving tweets more values & meaning.  Squidoo has a list The Only Twitter Applications List You'll Ever Need. Check out the list to find out Twitter Apps that suits your need. Many applications like Twitter Visualization are giving tweets a nice looks. Check out  the Twitter Vision app, it shows real time tweets in the global map.  Twitter fall is another app i enjoy. Mentionmap is one app that let’s you see your interactive nature in twitter, shows the network of people you frequently talk with in twitter. Here is the I love version of Twistori. Twistori grabs the tweets containing emotional words like Love, Hate, Think, Believe, Feel, Wish and shows them with a nice animation. If you want to get some positive feelings, you might enjoy looking at the real/tweet stories in the twistori application.

These are one set of application that add value to the tweet. Another set of application exists which add twitter use itself. Every web application these days supports twitter. With the very open API from twitter & some programming knowledge you can build an app for yourself. The availability of twitter apps for wide verity of use adds meaning to the point why one should twitter.

9th tweet:

9

It’s true, you follow Oprah Winfrey, and enjoy reading her tweets. How would the moment you react when she mentions you tweet??? Would you like to share this feeling ?

Wide acceptance of twitter from celebs has made it a place to be in, follow them. Enjoy their lifestyle. If you are in doubt whether she’s real Oprah or not go to her twitter and check for the badge – Verified Account above her name in profile page. If you want to know about what’s verified account read this page from twitter.

I enjoy listening to Coldplay. i follow them, yeah i follow the real Coldplay Band. Here’s how :

verified

Sharing about the moment like this, i discovered Jacqueline Bigar’s twitter after 4 or 5 months being in twitter. It was one of the best moment i had in twitter, really enjoyed following her. 

Some cool people i follow in twitter:

This guy sings for me, John Mayer
David Gray
Born to be DJ, Paul van Dyk,
Greenday
Jason Mraz
They are starting up, i enjoy their songs. Acid House Kings
Imogen Heap
He has become my favorite writer, Chetan Bhagat

10th tweet :

10

Yeah, It takes just 2 minutes to setup twitter, 2 days to grasp it, 2 weeks to gather some crowd & 2 months to addiction!

Setting up a twitter account is just few clicks. Provide your basic info, have a representing avatar and there you go. It’ll take no more than 2 minutes if you are going to try now. 

I was wondering how should i send my first tweet back then. Don’t worry, write whatever you have in your mind. It’s fine. Your profile, number of tweets, number of following followers will say you are the beginner. We will be happy to welcome you.

After setting up your account, give some time to understand the twitter itself. Learn what’s twitter. Twitter101 is excellent guide if you want to use twitter for your business. There’s one amazing article from Web Designer Depot, The Ultimate Guide for Everything Twitter. This article will help you understand basics of twitter, how to make your profile represent yourself,Twitter Etiquettes, twitter terms and everything else you need to know about using twitter. When i was beginning, I fortunately followed @mashable who became my twitter guru! They have setup excellent guide on twitter. Go through the guide to understand – the real value of twitter. Within two days of reading what’s twitter you’ll understand how the twitter works, value of your profile, mentions, retweets, hashtags, twitter lists & more. This will give you the feel about real value of your twitter. What i meant to say is, learn and know about the place you are going to be on forever onwards.

The first thing after setting up account people do is search for friends, celebrities & like minded people around. Use twitter search to find  your friends in twitter. Gather some crowd. Follow your favorite celebrities. Invite your friends to use twitter, the more friends you have around to interact  with the more fun twitter will become. You can follow me if you will. Don’t forget to mention you read this post.

Now you are ready to tweet on the go, the more you tweet the more chance that you’ll appear on twitter search and hence more like minded friends. Same applies when you search.

Tweeting is about sharing, the more you share the more you will be attached to the twitter. Look how exciting it becomes when a unknown friend from somewhere around the globe mentions you thanking for your last tweet. It becomes a habit, a lifestyle. If you were blogging till now, twitter will really fascinate you, it’s just about writing 140 characters with some meaning. One tweet will capture your one moment. It’s your life stream. Be true to what you are, do not show off. With your nearest circles all in the twitter it will become a day to day place to be in. Accept it as a place you value & you will be benefited. Within short time or not more than two months, i guarantee you’ll become addicted to tweeting. Don’t blame i didn’t warn you!

Welcome to twitter.

Wednesday, May 5, 2010

CodeIgniter Helpers – How to write your own?

Find yourself again and again doing CI or are you just getting started in to your next big project ? Get this book by Rob Foster. This is an easy-to-follow guide consisting of a number of projects that enable you to develop full-featured applications at a fast pace. CodeIgniter Web Application Blueprints

What is here:
         -> What is a codeigniter helper? an example
         -> Creating your own codeigniter helper, create a helper which will have a function to Check Ajax requests
         -> Accessing sessions/models from within Helpers
         -> A tip on how to load codeigniter models from within another model.

From CI site
Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular category. There are URL Helpers, that assist in creating links, there are Form Helpers that help you create form elements, Text Helpers perform various text formatting routines, Cookie Helpers set and read cookies, File Helpers help you deal with files, etc.

A helper can be loaded anywhere within your controller functions (or even within your View files, although that's not a good practice), as long as you load it before you use it.
Let me give you and example:
in controller, model or view you have to first load the helper you want to use with following line:
$this->load->helper('name');
where ‘name’ === is helper file residing in ===>  application/helpers/name_helper.php (custom helper if exists)
or system/helpers/name_helper.php (bundled with codeigniter)

name’ is the name you want for your helper, then a _ (underscore) & helper.php, the codeigniter’s way.
if you want to look at a sample: go check system/helpers folder, they come bundled with codeigniter. Here’s a snippet from: system/helpers/url_helper.php
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('site_url'))
{
    function site_url($uri = '')
    {
        $CI =& get_instance();
        //every time you need to use codeigniter system libraries or functions or model you’d do this      through the get_instance
        return $CI->config->site_url($uri);       
    }
}
Remember, when you used this site_url() function?? okay what you did was:
loaded the helper at your controller construction or where ever you needed using,  $this->load->helper('url');and simply echo site_url(); or like that. 

How to write your own helper  : Check Ajax Request using Codeigniter Helper

Yesterday, while going through my current project, I was calling lots of controller actions with jQuery Ajax and i was in need to check whether the call/request is made through Ajax or not in the controllers. Since i needed a way to use this facility in lots of controllers, i thought helpers would come handy here.
Rather than just copy/pasting the same lines of code in every controllers or at times you may need to use same functions in models & views too, it is good practice to make this function have some separate space in helpers (but not a good practice to load helper in views, see above, from CI site). So you should be clear at first whether your function need a place in helper or not??? Ask yourself  and decide for your work, if the frequency of your function call is going to be maximum, sure create a new helper or extend existing one. I decided to create one in my case.
Okay let’s make our Ajax request checker?? isAjax() function, residing in useful helper. When i Googled around for checking Ajax request i found a three line snippet here CHECK FOR AJAX REQUEST, i’ll will be implementing this for our purpose here. It goes like this:
function isAjax() {
return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
}
The Helper:
system/application/helpers/useful_helper.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
//secure your snippet from external access
function isAjax() {  
           return ( isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');  
      }
?>
Using in Controller: application/controllers/somecontroller.php
function submit_form(){
//function you call when you submit your form through Ajax. 
$this->load->helper('useful'); //load our just defined helper
if(isAjax()){
          echo ‘The request is made throug ajax. success!’ ;
          //do your stuffs
          exit;
       }     
}
 
Accessing session/models from within Helpers
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
      function isAjax() {  
           return ( isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');  
      }
     function check_login(){     
      //$userId = $this->session->userdata('userid); this line will not work here <<-----
       // you'd access your session variables through get_instance() as below
       $CI =& get_instance();
       //now session access through this instance
       $userId = $CI->session->userdata('userid);
       if ($userid < 0 ) {
              return 0; //user not logged in
           }
      else {
             return 1; user session exists, must be logged in 
           }
      }
  function hello_model_world(){     
        //or if you decided to load & use you models here
        //$this->load->model('Hello_model');   <---- this will not work too.
        //use as 
         $CI =& get_instance(); //first get instance
         $CI->load->model('Hello_model');  //then load model through instance.  
         //and calling a model function
         $data = $CI->Hello_model->display_this(‘hello world!’);
        //assuming your model returns capitalizing the initial letters of the words
         return $data; //will give Hello World! 
      }
?>
Now, you can easily load your helper in controllers & models and use it as regular helpers.

Extra tip about loading codeigniter model from another models:

You see how handy the $CI =& get_instance(); is in helpers. okay, let me add a quick tips talking about this, what if at times you needed to find out a way to load another models in your current model?? Ok here’s the solution:
<?php
class Test_model extends Model {
function Test_model()
    {
        //Call the Model constructor
        parent::Model();
    }
function do_something(){
//you wanted to load another model called Hello_model here in this function in this model class
//it’s okay
//use
         $CI =& get_instance(); //first get instance
         $CI->load->model('Hello_model'); //then load model
         $data = $CI->Hello_model->display_this(‘hello world!’); //call functions
         //do anything with this $data        
}
}
?>


Happy Coding.
Regards


Monday, May 3, 2010

Hello World – CodeIgniter Model – A Simple Bookmark Manager

Continued from Hello World – CodeIgniter!

I’ve been a bit busy with my development works. Talking about codeigniter,i will discuss today on how we can use it to access MySql database, insert data into tables, retrieve and display them, at times delete them. We’ll create a very simple Bookmark Manager App (just for the sake of understanding models in codeigniter, i’ve added code over the last article )

  what we’ll do today 

-1. if you don’t have codeigniter yet, download it from ci site.
0.rename extracted CodeIgniter zip folder to ci & add it to your server root - xampp/htdocs or wamp/www  folder
1. Database Design: create database & table representing our Bookmark Storage requirement & save some configuration setting so that codeigniter recognizes which database we want to work on.
2. Model: describe the database accessing logic (called business logic, it’s where the real business goes, your data will be your business & you’ll build logic over this business) – CRUD – create, retrieve, update, delete actions, in Models of the codeigniter
3. Controller: use the Controller to access data from the Model & pass them to View so that it can display them.
4. View: Create a simple View with HTML forms, that helps user with CRUD operations
5. Test

1. Create Database named ci_test going to http://localhost/phpMyAdmin, click on this database, there are zero tables yet.  copy paste the table structure by going to SQL link. and Go.

CREATE TABLE IF NOT EXISTS `bookmarks` (
  `bookmark_id` int(11) NOT NULL AUTO_INCREMENT,
  `url` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`bookmark_id`),
  UNIQUE KEY `url` (`url`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 ;

http://localhost/phpMyadmin Interface: Create table from SQL

You created your database & table.

Open application/config/database.php and change as followings

$db['default']['hostname'] = "localhost";  //hostname
$db['default']['username'] = "root";          //default user name in local dev environment
$db['default']['password'] = "";                 //default password is blank
$db['default']['database'] = "ci_test";       //our database
$db['default']['dbdriver'] = "mysql";          //we are going to use MySql database

leave others as default for now. Now you told codeigniter to use our database in the application we are going to build.

2. Defining Model (a PHP class that’ll wrap our relation database model to Object Oriented style)

Here Bookmarks_Model  is a  PHP class, file name bookmarks_model.php & with some methods inside it inside the Models folder,
filename: Application/Models/bookmarks_model.php
the relation between file name & class name is
classname = ucfirst($filename)  without .php extension ok //first letter uppercase

it will look like this

 

<?php
class Bookmarks_model extends Model {

    var $url   = '';
    var $description = '';   

    function Bookmarks_model()
    {
        // Call the Model constructor
        parent::Model();
    }
    function get_last_ten_entries()
    {
        $query = $this->db->get('bookmarks', 10);
        return $query->result();
    }

    function save($u,$d)
    {       
        $this->url = $u;
        $this->description = $d;               
        $this->db->insert('bookmarks', $this);       
    }
    function delete($id)
    {       
        $this->db->where('bookmark_id', $id);
        $this->db->delete('bookmarks');        

    }

    function update_entry()
    {
        $this->url  = $_POST['url'];
        $this->description = $_POST['desc']; 
        $this->db->update('bookmarks', $this, array('bookmarks_id' => $_POST['id']));
    }

}
?>

 3. Inside Controller

Here Hello is a  PHP class, file name helllo.php & with some methods inside it inside the controller folder. controller & function inside it are the only way user can interact with our system, that’s why we can say controller has control over the flow of the application, we’ll access this controller later as:  http://localhost/ci/index.php/hello and each function inside it as – see comment in the code.

The naming convention for filename & class name is
classname = ucfirst($filename)  without .php extension

filename: application/controllers/hello.php 

<?php

  class Hello extends Controller {
  function Hello()
    {       
        parent::Controller();
        $this->load->database();//load database library  
        $this->load->model('Bookmarks_model'); //load just defined model
    }

    function index($data='') { 
      //accessed from url when typed http://localhost/ci/index.php/hello
      $bookmarks=$this->Bookmarks_model->get_last_ten_entries();     
      //call the function inside model which returns last ten entries
      $data['bookmarks']=$bookmarks;                  
      //create $data array with the values returned from the model function
      $this->load->view("hello_view",$data);
      //load the view named hello_view.php passing $data to it.
    }

    function save()
    {     
     //accessed from url when typed http://localhost/ci/index.php/hello/save
     //retrieve data from the form post method
     $u=$this->input->post('url');    
     $d=$this->input->post('desc');            
     //check for validity
    if ($u==''&& $d==''){       
        echo "Invalid, Entry";               
    }
    else{       
    //if valid data, call the function of the model which will save our data
    //to database   
     $this->Bookmarks_model->save($u,$d);   
     echo "Thanks, Link Added!";        
    }
  }
  function del($id)
    {
    //del function is receiving data from URL
    //accessed from url when typed http://localhost/ci/index.php/hello/___id___
    //___id___ is the promary key of the data   
    //delete data by passing primary key  
    $this->Bookmarks_model->delete($id);
    echo "Thanks, Link Deleted!";                
  }
  }
?>

4. the view
no naming convention for a view. build your own but you should make it easier to link your controller action to view memorable. just remember you’ll load (like used to include) views using filename without extension in controller. if you like extension see user guide for more $this->load->view options.

filename: application/views/hello_view.php 

<h1>Bookmark Manager </h1>
//simple php for each loop to iterate throug our data
//remember $bookmarks was passed from the controller as index of the $data variable, which is accessed here as an array of object.
//if you want to view the structure of the $bookmarks array uncomment the line below this.
//print_r($bookmarks);
//initially the array will be blank, but will show it’s structure after you add some data using the form.

<?php foreach($bookmarks as $b) : ?>

<?php echo $b->description;?><br>
<a target='_blank' href='<?php echo $b->url;?>'><?php echo $b->url;?></a>
<a href='<?php echo base_url() .'hello/del/'. $b->bookmark_id;?>'> Del</a>
<hr>
<?php endforeach; ?>
<br><br>

//html form to help add data to the database

//the action of the form is defined as the save method of the hello controller.
// base_url() function gives the root path of this project
//defined in application/config/config.php as
//$config['base_url']    = http://localhost/ci/index.php/;

<form method="post" action="<?php echo base_url() .'hello/save'; ?>">
Url:<input type='text' name='url' > <br>
Description:<input type='text' name='desc' > <br>
<input type="submit" value="Add">
</form>

5. Now go test the application you just created.

 


Let’s memories $data flow in Codeigniter once

Model –  to – Controller – to – View   flow i.e.
from database to – [ PHP code to/Data Manipulation ] – HTML presentation

1. Go through the user guide, remember this, when you see the terms Model, View & Controller – you just keep focused in the PHP Classes inside  the folders named Models, Controllers & Views within the system/application folder of the codeigniter.

 

ci-mvc

Model – PHP files, each file, each class for each table in database or group as you like, application/models,
View – PHP files, each file, presentation for actions(methods/functions) in controller, application/views
Controller - PHP files, each file, each class that control application flow, application/controllers

2. when they say, build a model for your database, think that you are going to create PHP files, each for each table.. etc…  with a class with some function to access database (using SQL queries or ORM/object relation mapper or plane SQL) & return these data to controller as array or objects like you used to return 0;  in C/C++ main functions.

function get_last_ten_entries()
    {
       //codeigniters default ORM activerecord’s way to retrive data
       //produces sql like -- select * from bookmarks limit 10
        $query = $this->db->get('bookmarks', 10);
        return $query->result();//return data to calling function from controller, returns objects array
    }

3. When they say access data from the model – you’ll be calling from controller or view a function inside a codeigniter models php file to retrieve data from the database. like this.

//load model like you use to include dbconfig.php or whatever, wherever in controller you need
$this->load->model('Bookmarks_model');
//use the function inside it through the loaded model instance
$bookmarks=$this->Bookmarks_model->get_last_ten_entries();   //an object array  

data returned from model is stored invariable $bookmarks

4. when they say, pass data to the view, you’ll be using a simple codeigniter function to pass data to a function which is used to load view (php files inside the views folder).

why you accessed data in controller? obviously to display or act upon it: so let’s pass it to view that handles our display system, no data manipulation for now.

//create $data array with the values returned from the model function
$data['bookmarks']=$bookmarks;                  

//load the view named hello_view.php passing $data to it.
$this->load->view("hello_view",$data);

5. When they say, design/markup a view? you are going to add some PHP files in the Views folder, name it as you like but keep the name in order so that it’ll be easier to reference later which controller is calling which view??

//you passed the variable bookmarks from step 3(controller), to step 5 (view) in summary just above. now access it & display it.
<?php
foreach($bookmarks as $b) :?>
echo $b->description;
echo ‘<br>’;
echo $b->url;<hr>
endforeach;
?>

Hope this helps you to start out with CodeIgniter, you are ready to explore on your own now. 
Regards.

Sunday, May 2, 2010

Social Network Database Design Sample - MySQL

what?
------
sample database for a social network project – a mysql database schema
Database Engine: InnoDB (edit the mwb file if you need to change it to MyISAM or any other.)
the aspects of a social network i tried to cover in this database:
- user profile
- friends
- friends list
- status updates
- thumbs up/down status (these can be easily ported to other entities)
- bookmark saving
- rss/atom feeds saving
- notifications
- chat
- blog, site level not user level

user

- privacy
profile
why?
------
you can use these files for beginning a social n/w type projects in PHP/MySQL development environment.
when i was doing social network project, i searched here & there for database design of a social network, but what i found in the internet were not useful. they provided a introductory sketch about social network database structure but but as i had a limited  time frame for my project, those materials were not useful. i have analyzed most of the basic requirements for a  social network database structure, and sharing this with you so that it would save some of your time to start out your project. 
statusthe database is not completely normalized yet but you can edit it as per your needs. don't waste to much time on what  fields should i use for profile or for a status representation, these entity sets in the design will suffice in most of the cases. You can add entities for pictures, video, music sharing or anything you like. Just use the workbench design file.






Here are few books i'd recommend if you are willing to dive deep into MySQL and database designs

1. Beginning MySQL Database Design and Optimization: From Novice to Professional
or
2. High Performance MySQL: Optimization, Backups, and Replication

files included
-----------------
following files are included
sns.7.0-.mwb - MySql WorkBench Design
sns.7.0.png - exported PNG from MySql workbench
sns7.0.sql - exported SQL from MySql Workbench
sns.yml - Doctrine Generated schema in YAML
you can use the MySQL WorkBench Designer available Open Source at http://wb.mysql.com & begin with the mwb file,
change it for your need, export to sql & use it for your project.
Download MySQL Social Network Database Design – Sample

Update 11/14/2011:
Many readers have requested how the project ended up in look.
So, here goes the slide we presented to Tribhuvan University (with formal details cut out).
Thanks for reading this post.

TimiHami a Nepali Social Network