Saturday, September 25, 2010

Hello World - PyroCMS Module

/*---------------------------------------------------------------------------------------------
Update 10/16/2011:

This tutorial has been here for older version (< 1.0.x) of PyroCMS. Latest Stable PyroCMS release is v1.3.2
Please download and use following tutorial files which are for PyroCMS 1.3.2:

PyroCMS Hello World Module tutorial pdf for v1.3.2
Download Sample Hello World Module PyroCMS 1.3.2

Pyro docs have been significantly improved over the year. You can refer it too. If you need developers to work on your PyroCMS project you can contact us here - Semicolon Developers.

(Many thanks to Alan Martin from South Africa who forwarded me these updates.)

---------------------------------------------------------------------------------------------*/
PyroCMS Version: 0.0.9.9.x
What’s here:
------------------------------------------------------------
PyroCMS Module – Folder Location?
PyroCMS Module – Files Required & Folder Structure?
PyroCMS Module – Frontend/Backend Snapshot (of what we are going to build)
PyroCMS Module – Coding the Hello World module with full MVC implementation 
Why "<![CDATA  MySql stuffs     ]]>" required to be in correct format in details.xml ?
Hello world module Code
Summary
----------------------------------------------------------
With this text, I assume your familiarity with PyroCMS folder structure and theming, and you are testing on xampp.  I would explain how to make PyroCMS Module with very basic concepts from Codeigniter and PyroCMS.  Do double check what i have highlight here,  you may get errors installing/running the module we create, otherwise.
PyroCMS is good, but its documentation is not enough/not clear. I mean, once you know stuffs, its very easy to understand things at one shot, but it is rarely the case with beginners, that’s why i thought i would put the example on it.
Don’t copy-paste the code from the example below rather download source code from github, in copy pasting you might face quotes errors. mysql query might not work.

PyroCMS Module – Folder Location?

PyroCMS Core Modules
…..xampp\htdocs\pyrocms\application\modules\pages
”pages” is pyrocms core module that handles the pyroCMS page element

Custom Modules / Third Party Module / we are creating one now

Custom Modules are placed under projectname\third_party\modules  folder
xampp\htdocs\pyrocms\third_party\modules\helloworld
pyrocms – our project name
helloworld – the module we are going to create.
Remember Core and Third Party modules and their directories.

PyroCMS Module – Files Required?

PyroCMS requires at least a details.xml and one controller inside the module-name folder to be a module. I will explain file requirements for different types of module creation. Filenames and folders, are understood easily if you know Codeigniter MVC conventions. If you are not familiar with CI and trying to build PyroCMS module, still its easy to grasp the folder structure with one easy attempt like this. You can have following folders inside a custom module folder - config, controllers, helpers, libraries, models, views, js, css, img.
1. helloworld\details.xml
-> its basic structure is explained in detail below
-> this file contains module name, description, version etc.. and some useful configuration options that help PyroCMS understand our new module. Say Hello! Introduce your module here.
2. helloworld\controllers\helloworld.php
-> the name of the controller (file name & class name) keep them same as module name
-> If you need module just for front end and nothing required in backend, you’d need at least one controller, and extend the controller class from Public_Controller.
-> if you need to access these module from backend (like CRUD interface in backend), you’ll need  a controller class helloworld\controllers\admin.php which would extent Admin_Controller
When i write a file name like helloworld\controllers\helloworld.php i expect, you have created a helloworl.php controller inside controllers folder inside our helloworld module.
3. helloworld\views\helloworld.php
-> view file which would be used for displaying data from module controller
->If you don’t need to access database for your module these 3 files will suffice your need for creating module, otherwise you need model class too. Take your time to understand the folder structure.
-> if you thought to put backend admin controllers in setp 2 above, then think about placing its views too.

let’s place some view files as for admin side in a views\admin folder for easy structure: 

helloworld\views\admin\index.php
-> pass data to this view from admin controller
helloworld\views\admin\sidebar.php
-> sidebar partial that’s shown in left sidebar of the default backend theme.
-> partial is just few tags and php codes together. think of it as general “view file” . For eg. the box in the sidebar of other modules you see while browsing in admin.
4. helloworld\models\helloworld_m.php

So when we require database access or to implement business logic, we create models :
helloworld_m.php  <— this is a convention of underscore m, model class name would be Helloworld_m . You can create more model files as per your need.
Don’t forget to place these file on respective Models/Views/Controllers folder according the folder structure in the figure (at end of this section below)
1. helloworld\details.xml
2. helloworld\controllers\helloworld.php
      ----> helloworld\controllers\admin.php  [controller for admin interface]
3. helloworld\views\view_file.php
    -------> helloworld\views\admin\index.php –> admin main view
    ------> helloworld\views\admin\sidebar.php –> admin sidebar partial
4. helloworld\models\helloworld_m.php
If your module is complex, you end with more files, that’s okay.
PyroCMS module file/folder structure is MVC, just bundled within a module folder. That’s what makes PyroCMS HMVC ( Hierarchical Model View Controller). PyroCMS is codeigniter based, if you know codeigniter you have an option to understand HMVC and build your own CMS ;) Good Luck.

Here’s the PyroCMS helloworld module folder structure:
module_structure

PyroCMS Module – Frontend/Backend Snapshot

Let’s have a look at what our module will look in front-end and backend

Frontend: <h1><?php echo $msg; ?></h1> that’s it
front
(to see a module in action, we’d after installing helloworld module link one header navigation to our module)

Section of what you see when you add new navigation link:
link_module
Backend:

Module installed and listed in the Admin –> Modules-> Third party Section (we don’t create view for this listing, PyroCMS automatically lists our new module there if successfully installed, information is taken from details.xml)
modulelist
We have – index.php and  sidebar.php  for admin side view,
when we build template from these two view that will look as below on the admin side.
Hello World Module Page on admin side: 
 admin
noticed the – left sidebar? main content? helloworld link on the admin navigation, link to hello world module in the dropdown modules list ?

PyroCMS Module – Coding the module

The code is just for illustration purpose. My idea is to help you create and install your own custom module.

1. helloworld\details.xml
2. helloworld\controllers\helloworld.php
      a. ----> helloworld\controllers\admin.php  [controller for admin interface]
3. helloworld\views\view_file.php
      a. -------> helloworld\views\admin\index.php –> admin main view 
      b. ------> helloworld\views\admin\sidebar.php –> admin sidebar partial
4. helloworld\models\helloworld_m.php
we’ll create 1 (details.xml) + 2 (controllers) + 3 (views) + 1 (model file) = 7 files in total and respective folders Models\Views\Controllers and place them inside MVC folder structure.

1. helloworld\details.xml

A. basic file / when no backend and MySQL required:

-> When we don’t need custom table for our module in database or when we are just working on PyroCMS tables to access data, we can have a minimal details.xml as follows.
<?xml version="1.0" encoding="UTF-8"?>
<module version="0.1">
  <name>   
    <en>Helloworld</en>   
  </name>
  <description> 
    <en>Displays Hello World! Message to user</en>   
  </description>  
  <skip_xss>1</skip_xss>
  <is_frontend>1</is_frontend> 
  <is_backend>0</is_backend>
  <is_backend_menu>0</is_backend_menu>   
</module>

where:
<name> &  <description>  will help list the module in admin->modules->third party modules list.
<skip_xss>1</skip_xss> – skip_xss true
<is_frontend>1</is_frontend>  - front end of the module exists <is_backend>0</is_backend>  - module has no backend support
<is_backend_menu>0</is_backend_menu>   - module will not be listed in backend admin navigation
B. Advanced file / when backend of module exists and our module will have its own database table to operate:
<?xml version="1.0" encoding="UTF-8"?>
<module version="0.1">
  <name>   
    <en>Helloworld</en>   
  </name>
  <description> 
    <en>Displays Hello World! Message to user</en>   
  </description>  
  <skip_xss>1</skip_xss>
  <is_frontend>1</is_frontend> 
  <is_backend>1</is_backend>
  <is_backend_menu>1</is_backend_menu>   
    <controllers>
        <controller name="admin">
            <method>index</method>           
        </controller>
    </controllers> 
    <install>
<![CDATA[  
DROP TABLE IF EXISTS hello_world;
-- command split --
CREATE TABLE hello_world (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`msg` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE = MYISAM ; 
-- command split --
INSERT INTO `hello_world` (`id`,`msg`)
VALUES (NULL , 'hello world from PyroCMS module, from db'),
(NULL , 'Greetings from @bhu1st');
]]>
  </install>
<uninstall>
<![CDATA[
  DROP TABLE IF EXISTS hello_world;
]]>
</uninstall>
</module>
Did you see the changes??
is_backend set to one. i.e module accessible in backend. If database table are used just for storing information and no backend access required this can be set to zero.
<is_backend>1</is_backend>   - we are going to build module backend accessible
<is_backend_menu>1</is_backend_menu>  - module will be listed in admin side navigation menu  

Name of the admin controller and its methods

We add code  below when we create module that have backend interface.
<controller name=”admin”> tells we are going to create a
helloworld\controllers\admin.php  - controller
The controller that will extend Admin_Controller and we would have one method named index in it.
<controllers>
       <controller name="admin">
           <method>index</method>            
       </controller>
</controllers> 

MySQL Queries required at module install time
Before explaining this i want you to remember that details.xml file is a XML document.
Let me explain, What is this "<![CDATA  MySql stuffs     ]]>" doing here?

Everything inside a CDATA section is ignored by the XML parser, but will be used by PyroCMS module install routine.
XML Document Parser will parse all <element></element> but, characters inside the "<![CDATA  -----------    ]]>"  are not parsed by XML parsers and they are taken as raw string of characters.  So the advantage is we keep our required MySQL queries inside it, as normal storage. At XML document parse time (module installation),  the content between <install></install> is taken, split by the separator -- command split --  and executed over the PyroCMS database that we setup in PyroCMS installation process.
Remember:
a. Include your MySQL queries inside "<![CDATA” &    “ ]]>"
b. Separate each MySQL query by the separator
          -- command split --
c. the CDATA end marker ]]>" cannot contain spaces or line breaks before it. Just place it before </install> as

]]>
</install>

d. last query doesn’t need the -- command split --  separator
e. CDATA can not be nested 

So the code below contains two queries,  clear to see:

<install>
<![CDATA[  
DROP TABLE IF EXISTS hello_world;
-- command split --
CREATE TABLE hello_world (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`msg` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE = MYISAM ; 
-- command split --
INSERT INTO `hello_world` (`id`,`msg`)
VALUES (NULL , 'hello world from PyroCMS module, from db'),
(NULL , 'Greetings from @bhu1st');
]]>
</install>
In this CDATA section, we first drop the table “hello_world” if exists in database, then we create and insert some data in the hello_world table. That’s it. Our table is created and populated with the supplied data, if module installation went fine, you should be able to see the hello_world table in PyroCMS database you setup before.
MySQL Queries required at module uninstall time
  <uninstall>
<![CDATA[
  DROP TABLE IF EXISTS hello_world;
]]>
</uninstall>
If you grasped the CDATA concept, only thing that concerns us in <uninstall></uninstall> code is the MySQL query “DROP TABLE IF EXISTS hello_world;”, yup, this will be triggered when you uninstall the module.  That’s fine. Tables created during install time will be deleted.

C. When your module is just accessed in backend, like Newsletter module etc..

 
<is_frontend>0</is_frontend>
<is_backend>1</is_backend>
<is_backend_menu>0</is_backend_menu>
refer code above with these settings for full details.xml code..

2. helloworld\controllers\helloworld.php

Code/comment explains itself, you may refer above sections too.
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
|-------------------------------------
| Publich Controller of our module
|-------------------------------------
| accessed from front end
|
| extends Public_Controller
*/
class Helloworld extends Public_Controller
{
    function __construct()
    {
        parent::Public_Controller();
    }
    function index()
    {
        //load model
        $this->load->model('helloworld_m');
        //get message from model
        $message = $this->helloworld_m->getHelloMsg();
        //pass message and build template
        $this->data->msg = $message;       
        $this->template->build('helloworld', $this->data);
    }
}

2. a. helloworld\controllers\admin.php  [controller for admin interface]

The controller file name “admin.php” since we specified so in our details.xml

<controllers>
       <controller name="admin">
           <method>index</method>            
       </controller>
</controllers> 

The Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
|-------------------------------------
| Admin Controller of our module
|-------------------------------------
| accessed from back end
| extends Admin_Controller
|
*/
class Admin extends Admin_Controller
{
    public function __construct()
    {
        parent::Admin_Controller();       
        //load model
        $this->load->model('helloworld_m');   
        //set views/admin/sidebar as 'sidebar' partial,
        //that is to be shown on Sidebar section of backend
        $this->template->set_partial('sidebar', 'admin/sidebar');
    }
    //Show Helloworld message to admin
    function index()
    {           
        //function triggred when we click on the module name in backend in the menu
        //get message from model
        $message = $this->helloworld_m->getHelloMsg();
        //pass message and build template
        $this->data->msg = $message;           
        $this->template->build('admin/index', $this->data);
    }
}
?>

3. helloworld\views\view_file.php

<h1><?php echo $msg; ?></h1>

3.a. helloworld\views\admin\index.php - admin main view 

Hi,
<br/> <br/>
<h2><?php echo $msg; ?></h2>

3.b, helloworld\views\admin\sidebar.php –> admin sidebar partial

see how it is set as sidebar partial in constructor of our Admin controller 2. a. helloworld\controllers\admin.php

  $this->template->set_partial('sidebar', 'admin/sidebar');

this view file would contain following html:
<div class="box">
    <h3>About Me</h3>   
    <div class="box-container">
        Bhupal Sapkota<br/>
        Kathmandu, Nepal<br/>
    </div>
</div>
i’ve put a little bit info about me, never mind. Put any <html> or Pyro stuff you like there.

4. helloworld\models\helloworld_m.php – our model class

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
|-------------------------------------
| Model Class of our module
|-------------------------------------
| for database access
|
*/
class Helloworld_m extends Model
{
    function __construct()
    {
        parent::Model();
    }
    function getHelloMsg()
    {   
        //get hello_world table
        $query = $this->db->get('hello_world');
        //if module successfully installed and data exists in table, grab it, return it
        if($query->num_rows() > 0){
            $result = $query->row_array();
            return $result['msg'];   
        }else { //otherwise return simple hello message       
            return "Hello world from PyroCMS Module!";
        }
    }
}
?>


Install Helloworld Module

->Download code from Helloworld PyroCMS Module in Github

zip your module, and upload it from the Modules –> Third party section, Upload link
If your MySQL queries had no problems, you’d see hello_world table added in PyroCMS database. Helloworld module will be listed in admin navigation, modules list, in third party section.

When you uninstall

module gets deleted from third_party\modules\ folder. think of having a backup before uninstall.

Module In Action

Access module from Admin Navigation menu or type this in browser:

Backend:
http://localhost/projectname/admin/modulename

 http://localhost/pyrocms/admin/helloworld
Frontend:
Assign one frontend navigation link to point our helloworld module
http://localhost/projectname/modulename
 http://localhost/pyrocms//helloworld

Output Check

I have added validation in our model Helloworld_m,
function getHelloMsg()
    {   
        //get hello_world table
        $query = $this->db->get('hello_world');
        //if module successfully installed and data exists in table, grab it, return it
        if($query->num_rows() > 0){
            $result = $query->row_array();
            return $result['msg'];   
        }else { //otherwise return simple hello message       
            return "Hello world from PyroCMS Module!";
        }
    }
If SQL executed successfully during module install, the $msg in view renders “hello world from PyroCMS module, from db” otherwise  "Hello world from PyroCMS Module!";

Conclusion

1. follow the file/folder structures and naming conventions.
2. Understand the module creation requirement and accordingly settings in details.xml
3. CDATA section of the details.xml needs to carefully saved. Check your queries in database before saving them in CDATA section.
4. Upload your module to install it.  [ remember to upload zip file, zip file name same as module name ]
[helloworld.zip] or [yourmodule.zip]
5. If upload failed, delete raw upload from third_party modules folder, database column if any, check your settings, check queries again, zip it, and re-upload.
5. If still couldn’t install it:
--> i think you now understand the module creation flow
--> insert few queries in database  [details.xml]
-> add your module settings in modules table in database [details.xml]
-> don’t wait for any other documentation ;) the kickass CMS, created over the kickass framework is really easy to grasp in one shot back tracing, 2-3 hours max  
-> hack it use it. contribute back if any.
-> if you are familiar with Codeigniter and not with HMVC  <------ read

Friday, September 3, 2010

Lorem Ipsum को कथा

Do you design, be it graphics or web design? or any other form of design type settings? Have you ever used Lorem Ipsum? What is your experience using Lorem Ipsum when designing for Nepali Unicode content?  

"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

You might have guessed till now, i am talking about the dummy text, yes Lorem Ipsum is a placeholder text, or filler or dummy text, that designers throughout the world use when working on  visual designs, web designs, any typographic work. If you are not familiar with Lorem Ipsum, i guess you are not in design. I might be wrong though, you should use it. Here is the reason why below.

Visit any site from Free Css Templates or search google for CSS layout, Photoshop design layouts or any sample design content of your interest  - you will end up with a nicely done design and Lorem Ipsum used as placeholder text.

If you like to know more about Lorem Ipsum, it’s history refer this wiki article or www.lipsum.com can be handy for you when working on designs and need a quick copy/paste version  of Lorem Ipsum.  We can find many Lorem Ipsum text generators that can give random latin text mixed up in paragraphs that can be sample content for us when designing web layouts. 

If you use Ms-word try typing following text in there to produce random lorem ipsum text


=lorem(i)

where,  i = natural number , genarates i paragraphs of random text

= lorem (i, j )

where i,j are natural number, where i = number of paragraphs and j = number of sentences per paragraph

 

Why Lorem Ipsum ?

Here’s a excerpt from wiki:

Even though using "lorem ipsum" often arouses curiosity because of its resemblance to classical Latin, it is not intended to have meaning. Where text is visible in a document, people tend to focus on the textual content rather than upon overall presentation, so publishers use lorem ipsum when displaying a typeface or design elements and page layout in order to direct the focus to the publication style and not the meaning of the text

Hope the idea is clear. It would always be better to use neutral content when presenting designs to our clients. That way we can, direct their focus on the look and feel of the design rather than on the sample content. Further, that sample content can be offensive sometimes.

i am working on a Nepal web site design, where i need all contents to be in unicode version. Traditional true type font would not render correct on every browser but thanks to unicode that we now can freely write नेपाली/Nepali anywhere in web and worry less about whether it will render correctly on the browsing end or not.

Here  i faced a problem, i was designing all sort of layouts for the site with Lorem Ipsum text, when design got ready and verified by my client (i convinced them all the text would be in Nepali in final version). Then, i started replacing dummy text with some Nepali unicode content! Huh, wtf? Did you know, the layout was all rendering
badly. All my effort for fixing the font size, margins, paddings – oh my, now i have to change them all to fit my Nepali unicode content. That was a complete waste of time.

Here’s a snapshot from sample free css template:  just for illustration
original

Noticed the font size 3em there in the <h1> style rule? See how nicely the “Welcome to my website” fit in the layout??  Below is the snapshot when i tried changing content 
to Nepali unicode.

 before0

Can you see the font-size:3em on Firebug inspect? Hope you can. But with this style rule our content looks a bit tangled, and not fitting nicely in the overall layout. And below i tried playing with different font size to fit the content: here’s the snapshot

after0

I went on replacing contents and changing css rules to fit my new content. I think, the scenario has always been like it when any of we worked on such projects. You might say that, the length of the text has destroyed the layout, yeah a sort of that too is responsible for the destroyed layout but i have here something more to say. 

Lorem Ipsum = ?

Wiki says,

A close English translation for Lorem Ipsum might be "pain itself" (dolorem = pain, grief, misery, suffering; ipsum = itself) .

 

If we want to say it in Nepali – it would translate as : दुख आफैमा

Below are two paragraphs that are mostly used as lorem ipsum text, which is in latin. The text is derived from Ciero’s De finibus bonorum et malorum (On the Ends of Goods and Evils, or  [About] The Purposes of Good and Evil ); Ciero was a Roman Philosopher/(106 BC) of the time.

The original version (with the excerpted items highlighted –which we are using now). Read the text in bold and you’ll catch the Lorem Ipsum dolor sit.. flow which sounds familiar, ain’t it?

Section 32/33 of the Book

[32] Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit amet, consectetur, adipisci[ng] velit, sed quia non numquam [do] eius modi temporainci[di]dunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui doloremeum fugiat, quo voluptas nulla pariatur?
[33] At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat..

Below is the english translated version of the original latin text:

H. Rackham's 1914 translation (with major source of Lorem Ipsum in bold)

[32] But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?
[33] On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.

Lorem Ispum for Nepali Desigs?

Like the development or design situations i mentioned above, what if we had any standard dummy text to be used ? This was just what i thought for the moment when i suddenly realized that  i need to replace all those sample Lorem Ipsum content with something that looks random unicode nepali content. So sad, we don’t have one!

I have argued above that, content to be used as placeholder text shouldn’t have any sensible meaning. But it was my curiosity that led me to go through what is their behind the Lorem Ipsum text.  I ended up with my own interpreted, Nepali version of Lorem Ipsum or say दुख आफैमा version.

i don’t understand latin, neither google translate helped here, with reference to the English version, Oxford Dictionary and our Nepali Shabdakosh, and few other English-Nepali/Nepali-English dictionaries, below is what i ended up in:

Closely look at the original text in latin – section [32], the Lorem ipsum passage starts at: 

Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit 

Which would mean:

"Neither is there anyone who loves grief itself since it is grief and thus wants to obtain it"

or  in Nepali

को नै छ र यहाँ जो दुख आफैमा मन पराउछ, किनकि यो दुख हो, त्यसैले त उ यसलाई पाउन चाहन्छ

Translation to [32]

तर मैले तपाइहरु सबैलाई भन्नैपर्छ, कसरि अबुद्धियुक्त तरिकाले सुख लाई बद्ख्वाई गर्ने अनि दुखलाई प्रसंशा गर्ने सोचको जन्म भयो, साथै म तपाइलाई यो प्रणालीको इतिबृति दिनेछु र सत्यको खोजि गर्ने महान खोजिकर्ता, मानब सुखको प्रमुख निर्माणकर्ताको सच्चा दर्शनहरुको बर्णन गर्नेछु | कोहिपनि सुखलाई यत्तिकै अस्विकार गर्दैन, मन पराउदैन वा नकार्दैन, किनकि त्यो सुख हो, तर किनकि उ तर्कसंगत ढंगमा सुखको खोजि गर्न जान्दैन अनि अत्यन्त दुखदायी परिणाम भोग्न पुग्छ | त्यसरीनै, कोहिपनि त्यस्तो छैन जो दुख आफैमा मन पराउछ, खोज्छ वा चाहन्छ, किनकि त्यो दुख हो, तर किनकि कहिलेकाही त्यस्ता परिस्थितिहरु देखापर्छन जसमा कडा परिश्रम र दुखमा नै उ कुनै अपार सुख प्राप्ति गर्छ | एउटा सानो उदाहरण लिनुपर्दा, हामीमध्य कति छौं जो निरन्तर कठिन शारीरिक कसरत गर्न तत्पर हुन्छौ, यसबाट केहि फाइदा लिने बाहेकको अरु कुनै कारणमा ? तर कोसंग के अधिकार छ, त्यस्तो मान्छेको गल्ति औल्याउने जो त्यो सुख छान्छ जसमा कस्टदायी परिणाम छैनन ? अथवा त्यस्तो मान्छेको जो त्यो दुख त्याग्छ जसमा कुनै सुखदायी परिणाम छैन ?

Translation to [33]

अर्कोतिर, हामी नैतिक रुपमै बद्ख्वाई गर्छौ र मन पराउदैनौ, त्यस्ता व्यक्तिहरु जो कुनै क्षणिक सुखको बान्कीहरुको हर्ष र आस्चर्यमा छलिएका अनि अनैतिक भएका, इच्छाहरुमा यति अन्धो भएका कि, उनीहरु पछी आउने दुख र अप्ठेरो देख्न सक्दैनन; र उत्तिकै दोष तिनीहरुमा पनि जान्छ जो कमजोर संकल्पको कारण आफ्नो कर्तब्यमा असफल हुन्छन, यो कडा परिश्रम र दुखले पूर्णरुपमा संकुचित हुनु भन्नु जस्तै हो | यी मामलाहरु छुट्याउन एकदम सरल र सहज छन | कुनै फुर्सद को समयमा, जब हाम्रो इच्छाशक्ति स्वछंद हुन्छ र जब हामी आफुले उत्कर्षमा गर्न चाहेको केसैले प्रतिबन्ध गर्दैन, सपूर्ण सुख स्वागत गरिनुपर्छ र सपूर्ण दुख त्यागिनुपर्छ | तर केहि खास परिस्थितिहरु र कर्तब्य को परिबन्धहरु अथवा ब्यबसायिक दायित्वहरुमा, धेरैजसो यस्तो लाग्छ कि सुखहरु छाडिनुपर्छ अनि झिजोलाग्दो कुराहरु स्विकारिनुपर्छ | बुद्दिमान मानिस त्यसैले यस्ता मामलामा छनोट को यो सिद्धान्तमा अडिग हुन्छ : उ सुखहरु त्याग्छ ता की अरु ठुला सुखहरु सुरक्षित गर्न सकोस, वा उ दुखहरु सहन्छ ता की अरु नराम्रा दुखहरु भोग्न नपरोस |

Wow! What the insight. I nodded, Lorem Ipsum is the secret to pleasures and pains in life. On completing this translation and re-reading actually felt like happiness and sadness are mere the choices in life, the idea is we should know how and when to choose one. We have to choose both, but circumstances matter!

But, still, after going through the two paragraphs overnight, i was in confusion how to interpret the first line:

"Neither is there anyone who loves grief itself since it is grief and thus wants to obtain it"

As

 को नै छ र यहाँ जो दुख आफैमा मन पराउछ, किनकि यो दुख हो, त्यसैले त उ यसलाई पाउन चाहन्छ

i chatted with my gurus, discussed with my colleagues and I skyped with my friends about how can we interpret the meaning. We had some discussions:

Here are some lines my friends shared when i asked for the interpretation:
- दुखलाई माया गर्ने कोहि छैन, किन कि त्यो दुख हो, तर दुख चाहिन्छ
- कहिले काहीँ दुख पनि रमाइलो बनिदिन्छ

The meaning of the line sounds more profound when we read it like:

बुद्दिमान मानिस सुखहरु त्याग्छ ता की अरु ठुला सुखहरु सुरक्षित गर्न सकोस, वा उ दुखहरु सहन्छ ता की अरु नराम्रा दुखहरु भोग्न नपरोस,  …… को नै छ र यहाँ जो दुख आफैमा मन पराउछ, किनकि यो दुख हो, त्यसैले त उ यसलाई पाउन चाहन्छ |

Here is how the CSS template that i was playing around for the illustration, ended up filled with this translated Nepali text as a sample/placeholder:  http://bit.ly/nepsum

I concluded the experience as,  we need to find some Lorem Ipsum text that preserves the uniqueness and beauty our language, that encourages our designs on our own.

If you are now reading this line, i guess, you are, please do share some words about the post and also i would love to hear your views on better translation.

References:

- The template is used from http://www.freecsstemplates.org/
- Lipsum Web site : http://www.lipsum.com/
- Wiki Article about Lorem Ipsum: http://en.wikipedia.org/wiki/Lorem_ipsum
- http://www.dictionary.com.np
- http://www.nepalisabdakos.com/
- Project I am involved in : Shabdasamyojan

Thursday, August 12, 2010

Nepal In - PHP Arrays

What is Nepal in PHP Arrays - Project ?
 
Are you a PHP developer in Nepal ? or do you use MySQL in your projects. How many of you have easier access to the places & cities of Nepal in simpler arrays, that can be taken for reference and used.

I am currently involved in a project named Gharbeti.com (get updates here ) and got in situation where i need to use the places in Kathmandu to implement the site theme. Gharbeti.com – The Rentals Solutions In Kathmandu.

I was searching through web, searching for some arrays of places, cities, districts headquarters etc. But i was not lucky enough to find them. Instead i thought i would search for places and list them as PHP Arrays or MySQL tables. This wiki page was handy though.

There is a project named PHP Arrays in Github -  I was solely inspired by this project. But, limiting myself to my country i decided to list resources related to Nepal in PHP arrays. This was how all it begun.

What is included in this project till now:

1. Places In Kathmandu - PHP Array & MySQL table
-> listing of most popular places in Kathmandu.
    -places_in_kathmandu.php
    -places_in_kathmandu.sql   


2. 14 Zones & 75 districts of Nepal
    -> 14 Zones (Anchals), 75 (Districts/Headquarters)
     -14_zones_75_districts_of_nepal.php


3. 75 Districts of Nepal and their Latitude & Longitude values.
    -> 75_districts_latitude_longitude.php
    -> If you want to calculate Latitude Longitude values by yourself: here's a little snippet using Google Maps API that we can loop through by yourself.

        $country = "Nepal";
        $city = "Kathmandu";
        $addEncoded = urlencode($country).",+".urlencode($city);
        $geoCode = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".$addEncoded."&sensor=false");                   
        $response = json_decode($geoCode);
        $lat = $response->results[0]->geometry->location->lat;
        $lng = $response->results[0]->geometry->location->lng;


    -> Pick up any latitude, longitude pair and try browsing in the following link format:
        This link should bring out Map for Chitwan district

 

Do you want to contribute to this Project?

Use the github repo url, clone a local copy or fork it, add files and push the changes.

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







Monday, March 22, 2010

Blogger Post & Comment Feed URLs

Recent Posts RSS feed url
http://yourBlogAddress.blogspot.com/feeds/posts/default

Recent Comments RSS feed url
http://yourBlogAddress.blogspot.com/feeds/comments/default

Label Specific Feed url
http://yourBlogAddress.blogspot.com/posts/comments/default/-/labelname

Replace -> yourBlogAddress with your actual blogger address.
Replace -> labelname with your label

Hope That Helps.

Sunday, March 21, 2010

Hello World – CodeIgniter!

So you decided to learn CodeIgniter PHP MVC Framework. I am too starting with it and planning to post a series of introductory tutorials on it. Here i go with – Hello World example in CodeIgniter.
Install Code Igniter
http://codeigniter.com/

Download CodeIgniter copy form the above site. The version i am using is 1.7.2
I assume you have setup your local development environment installing XAMPP bundle, and your browser shows http://localhost correctly. Otherwise you may want to refer Starting with PHP.
Let’s Begin.
Unzip the CodeIgniter file you downloaded to your root folder. You’d have a folder named CodeIgniter_1.7.2. Open it and see how files/folders are organized their.
If everything went ok, try entering http://localhost/CodeIgniter_1.7.2/ or http://localhost/CodeIgniter_1.7.2/index.php in your browser. you’ll have the default CodeIgniter page welcoming you.
We’ll learn to define our Hello World page as the index page at the end of this article.

Understand the folder organization

Here i have a snapshot of the structure of the CodeIgniter folder. Look carefully at the folder organization here. I will complete this tutorial explaining this figure.


codeigniter


As you can see.. there’s the system & user_guide folder, index.php and license.txt file in the extracted folder. Inside system folder there’s application folder. which is the main folder that contains our Web Application files. Other folders inside the system folders are Framework’s folder and we don’t need to change them at this time.
You can see CodeIgniter has wrapped the M – Models, V – Views and C – Controllers inside the application folder. You’ll get use to these and other folder slowly.
models folder – used to represent classes and object, which will interact with the database.
views folder – this is where we define the presentation or our web layouts.
controller folder – all the logic of the web application will be written inside controller folder, in simple php files. Each file contains a class definition and a class would have methods inside it.



Role of the controller
Controller is the main entrance to your web app. Whatever you’d do to interact with the web application all web request you make will reach the controller and handled by it. It plays vital role in the application structuring.

Our database requirement and data accessing classes will be defined inside the models folder in simple php files. The controller will make use of this classes to access data and pass the accessed data to the view i.e where user can see the result.
STEP 1:

Simply, create a file hello.php inside the controller folder. Copy & paste the following code. The code is simple and the comments will clear things.



<?php 


class Hello extends Controller {

function index() {

$data['helloMsg'] = "CodeIgniter says, Hello world!";
//Data is passed from the controller to the
//view by way of an array or an object in the
//second parameter of the view loading function.
$this->load->view("hello_view",$data);
//Where hello_view is the name of your view file.
//Note: The .php file extension does not need to be specified
//u
nless you use something other than .php
}

}
?>


The name of the class is Hello with capital H and the file name is hello.php, you should understand this convention. We simply define a class Hello that extends the base class Controller which will allow us to use inherited methods from this base class.

$data['helloMsg'] = "CodeIgniter says, Hello world!";

We have defined a $data array with helloMsg as index. The controller passes data either in Array or in Object form to the view. This is the reason why we didn’t make a simple php variable to pass data.

$this->load->view("hello_view",$data);

Then we passed the $data variable to the hello_view. which is the view we’ll use to display this data. The index ‘helloMsg’ will be available to the view as $helloMsg variable, simple. hello_view is simply a php file inside views folder created as follows.

STEP 2:

Now, create a file hello_view.php inside the views folder. Copy & paste the following code.
<h1> Welcome to CodeIgniter. </h1>
<?php echo $helloMsg ?>
Since it’s the view part and as i already mentioned we can use our HTML knowledge as far as we can. I have added two kind of text here for illustration, the normal HTML <h1> tag and other printed from the dynamic variable. $data variable was passed from the controller to the view, and hence $helloMsg its index is available here in view. We use simple php echo to display it.


STEP 3:

We are done. Now it’s time to test it. http://localhost/CodeIgniter_1.7.2/index.php/hello try typing this in the browser. If everything worked fine you’d see this output:


Welcome to CodeIgniter.

CodeIgniter says, Hello world!
DEFAULT CONTROLLER
(Setup your hello.php as default controller)
Okay, since we have successfully passed data from controller to the view to render it, now let’s define our hello class as the default controller of the application we are going to build. For this open the routes.php file inside the application/config .
find this line
$route['default_controller'] = "welcome";
and change it to
$route['default_controller'] = "hello";
okay it’s done now, try

http://localhost/CodeIgniter_1.7.2/index.php/hello
or
http://localhost/CodeIgniter_1.7.2/index.php
both will output our hello_view file.

SUMMARY

We understood the organization of folders in CodeIgniter, and their functions. We created our own controller, passed some data from controller to it’s corresponding view, displayed it there. and finally we made our custom controller as the default one. Now you can extend it someway, try adding some cool HTML/CSS/JavaScript in the view & try storing passing data from controller. By then, you’d created a simple web application.
This might seem like we just stored some values in PHP array and displayed as in old general fashion, but what’s the difference here? It’s different – now we’ve accomplished Hello World! output from a MVC framework. Yeah, now we have the full control of our web application from within a framework. You’ll feel more organized and managed once you get used to this MVC separation in CodeIgniter. Also, we can use extensive resources and help available in CodeIgniter site & online.
I suggest now, go through the user guide included in the CodeIgniter folder and understand more about Controller & Views. I’ll try to cover Models and how they are used in later covers.

http://localhost/CodeIgniter_1.7.2/user_guide
or
http://codeigniter.com/user_guide/