Friday, December 16, 2011

Dynamic database connection in CakePhp

I encountered this scenario at work wherein I have the same logic, same structure but using different brands. The problem is their database name and connection is different. Below is the solution I found:

Step 1: Create your database connection in database.php
var $brandXConfig = array(
 'driver' => 'postgres',
 'persistent' => false,
 'host' => 'localhost',
 'login' => 'root',
 'password' => '',
 'database' => 'brand_x',
 'prefix' => '',
 //'encoding' => 'utf8',
);


var $brandYConfig = array(
 'driver' => 'postgres',
 'persistent' => false,
 'host' => 'localhost',
 'login' => 'root',
 'password' => '',
 'database' => 'brand_y',
 'prefix' => '',
 //'encoding' => 'utf8',
);

Step 2: Add this function to app_model.php
Class AppModel extends Model
{
     function changeDataSource($newSource)  {
          parent::setDataSource($newSource);
          parent::__construct();
     }
}

Step 3: Add this function to app_controller.php
Class AppController extends Controller
{
     function changeDbSource($database = 'default') {
          $db = ConnectionManager::getInstance();
          $connected = $db->getDataSource($database);
          if($connected->isConnected()) 
                return true;
          return false;
     }
}

Step 4: Add this to your model
function changeMyDb($brand)
{
     if($brand == 'brandX') {
          $this->changeDataSource('brandXConfig');
     }
     else if($brand == 'brandY') {
          $this->changeDataSource('brandYConfig');
     }
}

After doing this, you'd be able to change your database connection as needed.

Wednesday, December 7, 2011

Change username or password of database

Database security concerns the use of a broad range of information security controls to protect databases (potentially including the data, the database applications or stored functions, the database systems, the database servers and the associated network links) against compromises of their confidentiality, integrity and availability.

One of the things you should do to secure your data is to change the username and password of your database. It is quite easy to do, just remember that if you change it, make sure to also change your settings in your application.
I am using wamp server and mysql as my database. Here are the steps to do this:
  1. Open config.inc.php. Mine is located at C:\wamp\apps\phpmyadmin3.2.0.1
  2. Change the settings for username and password. By default, it is set to 'root' and empty for password. In the figure below I changed my username to 'mynewuser' and my password to 'asdfgh'. Of course you could change it to something more secure.
  3. Fig 1: Sample of config.inc.php
  4. Lastly, Restart your server so changes will be on effect.

It's easy and makes your database more secure.

Sunday, November 27, 2011

Fastest PHP Framework

A web application framework is designed to support the development of dynamic websites, web applications and web services. It aims to alleviate the overhead associated with common activities performed in development such as database access, templating frameworks and session management, and it often promotes code reuse.

I have been coding Web Applications using PHP for a while and I find frameworks as very useful. It has an MVC (Model-View-Controller) approach, enforces good coding standards, has helpers and components which makes my coding life easier and saves me a lot of time and effort with its features. I and my officemates have been using CakePHP as our PHP framework for awhile and we think that its performance is becoming slow. We're thinking of trying out CodeIgniter, another famous PHP framework, but it makes me wonder, if it really is the fastest and most feature friendly framework we are looking for?

I did some research and I found DooPHP has quite an interesting portfolio.
Fig 1: DooPHP benchmark as of Febuary 25, 2011
DooPHP is claiming it might be the fastest MVC based PHP framework in the world. Beside that, it comes with features essential to today's Web 2.0 application development. It focuses on 7 main cores: MVC, REST, URI routing, ORM, Template engine, ease of use and performance. It even has a very loosely coupled design where developers can modify and add new functionailies to the framework easily.

Quite interesting right? What's not to like in this framework? Well for me, since it is still relatively new (started in 2009), I don't think it has a wide support base unlike its predecessors. Also, it feels like a hybrid framework. Why? One of the reasons why we use frameworks is because of its support for MVC.
function signup_action() {
/* Set the pages title */
$this->data['pagetitle'] = 'Signup';
// Load the User Model
Doo::loadModel('User');
// Get a new User Model Instance
$user = new User;
// Try and find a User with the specified username
$result = Doo::db()->find($user, array('limit' => 1));
}
In this example, we can see that it is accessing its data through the controller. That is not a good practice for "FAT MODELS, THIN CONTROLLERS" approach. It destroys the ideal MVC. Sure, it is faster but maintainability and reusability wise, it could be a pain in the future. For small scale projects, this could work since maintainability won't be much of an issue. Also, I get the feeling that it is like I am using classic PHP because I have to do/declare everything by myself as shown below:
Doo::loadCore('db/DooModel');
class User extends DooModel {
    public $id;
    public $username;
    public $password;
    public $group;

    public $_table = 'user';
    public $_primarykey = 'id';
    public $_fields = array('id', 'username', 'password', 'group');

    function __construct(){
        parent::$className =;__CLASS__;
    }
}

The closer you are to classic PHP, the faster your codes will be. Rasmus Lerdorf, the Godfather of PHP himself, believes that frameworks aren’t that great because they perform much slower than simple PHP. If you have to use a PHP framework, Rasmus likes Code Igniter the best, as it is "least like a framework"[2008]. We all have different needs, different wants and it all boils down to which framework will suit it. DooPHP is still young. It might be the fastest because it is almost similar to classic PHP, but it might be problematic in terms of scalability. Maybe after a few more years and this will be a framework to watch out for!

For now, I think I'll stick to CakePHP and will try its new stable version 2.0. :)

Other helpful resources:
DooPhp model guide
Learn DooPhp
10 Principles of the PHP Masters
CakePHP Best Practices: Fat Models and Skinny Controllers

Friday, November 25, 2011

JSON encode auto sorting issue

JSON is used to send data as an object either be an array or string.

I used AJAX to pass on my data from server to client. My intention was to populate a drop down list with values dynamically. I had created my array list as show below:
$result = array( '5' => 'a', '2' => 'b', '3' => 'c', '4' => 'd', );
echo json_encode(array( 'result' => 'success', 'details' => $result ));

I was expecting to see my array as is, but I was confused when I checked my JSON result array was as shown below:
array { result: "success", details: [{ 2: "b", 3: "c", 4: "d", 5: "a" }] }

See the problem? My array values were automatically sorted out. I found out that this is a browser issue with Google Chrome. I checked this using Firefox and there was no problem. So what is the solution to this problem? There are two ways:
  1. Don't use json_encode. I used this method because I realized I didn't really need to populate my dropdown list dynamically. I just needed static data for selection.
  2. Sort it out before appending to its drop down element.
  3. // data.details came from json_encode in the example above. 
    //arrVals should be an array.
    var arrVals = data.details();
    arrVals.sort(function(a, b){
        if(a.val>b.val){
            return 1;
        }   
        else if (a.val==b.val){
            return 0;
        }
        else {
            return -1;
        }
    });
    

Hopefully, Google Chrome will fix this bug so we won't encounter this again or performance will not be wasted.

Sources:
Sorting (dropdown) Select Options Using jQuery
Sort a select list box

Wednesday, November 23, 2011

CakePHP vs CodeIgniter

Web application framework, a software framework for development of dynamic websites, web applications, and web services

Nowadays, framework is important for us to create an agile, self-documented and organized Web Application. There has been a long fuss between these two great frameworks: CakePHP and CodeIgniter. But the question still remains, which framework should I choose? Read on to find out.


Fig 1: CakePHPFig 2: CodeIgniter

Both CodeIgniter and CakePHP are best suited for object oriented programming and support the Model View Controller architecture which provides robustness and flexibility to a great extent. CakePHP is the better one when it comes to robustness and strictness of conventions, which is appreciated by a section of the programmer community because it is easy to remember. On the other hand, venturesome programmers see this as a shortcoming in CakePHP. CodeIgniter has a wide built-in library that serves most of the purpose of a beginner in PHP programming. For those ahead of the rest, CodeIgniter lets them create their own libraries or rather classes within those libraries barring the database classes. There are certain simple naming conventions that need to be followed. The flexibility of creating custom classes and modifying existing native classes is something highly appreciated by radical programmers, always itching to create something different. CakePHP on the other hand, is more in demand with hard core PHP guys for its robustness and superior auto-load features. ORM is another strong point of CakePHP. In terms of speed, CodeIgniter wins hands down.

Both CakePHP and CodeIgniter has an active community and is open-source so development and improvements are continuously being done. They say clarity of documentation and online support community of CodeIgniter is far better than CakePHP, which makes it the framework of choice for toddler programmers and experts alike. For me, I prefer the documentation of CakePHP. Recently, they updated their website and I like the changes because now the community can edit the documentation. It is also easily searchable and well-organized; There is a blog tutorial that will easily help you jumpstart in getting used to CakePHP.

Bottomline, if you're a beginner you're best bet will be using CodeIgniter because it is closer to classic PHP, faster to learn, easy to use and fast. Otherwise, choose CakePHP for its strict MVC, robustness, data sanitation, and support for PHP4 and PHP5.

Monday, November 14, 2011

JQuery Scroll to top plugin

I am using this template at work and I find this plugin to be cool and useful. It's a JQuery Scroll to Top Dynamic Plugin by Matt Varone! It is a good UX design especially when you have a lengthy website and it is very easy to use.

Fig 1: Screen shot 

STEP 1: DOWNLOAD FILE

You may download file by clicking this link or manually download it by visiting Matt Varone's website

STEP 2: INCLUDE JAVASCRIPT AND CSS FILES










STEP 3: ADD THE MAGIC WORDS



Easy right? Try it out!

Reference: UItoTop jQuery Plugin - Matt

Tuesday, November 8, 2011

Typography

Imagine a world where writing does not exist. Where people rely on the human senses to remember things, to pass on the knowledge and explain what is seen. The world would have been a chaotic world. But when writing started to exist, everything seem to change; There was order; There was peace; Technological advancement and sharing was possible. Writing came in different form also known as Typography. Wikipedia defined it as:
"Typography is the art and technique of arranging type in order to make language visible."
A simple change in spacing and sizing could make a huge difference in your art work. What differenciates a professional looking work to an amateur work boils down to the typography used. Here are some pointers to remember:

  • Mix Seriff and San Seriff. (I used Arial and Georgia in the example below.)
SmallVille
  • When using two or more fonts, match the max height of small letters. (I used Verdana and Georgia)
ScriptCity

If you will compare both examples, You will notice that "ScriptCity" doesn't feel right, as in there is something off.

POINTERS TO REMEMBER:
  • Make use of font face that are meant to be used for each other. Some of the font face that are meant for each other are Arial and Georgia. 
  • Instead of placing letters vertically, just rotate the letters 45 degrees
  • Lastly, mind the spacing. Left-align is the best option for readability.

Any other opinion regarding typography? Pitch in your ideas at the comment section.

Thursday, November 3, 2011

User Design Experience

I was browsing and reading random IT-related websites I bumped to this article "The Role of Design in the Kingdom of Content" by Smashing Magazine. It talks about the importance of user design experience. Fascinated and curious of its contents, I started reading it. Here's what I learned:

PERSONAL ENGAGEMENT

Act on the opportunity the right way by using design to highlight the site's most valuable content. Build designs suitable with your content. Use visual tools like lines and shapes not just for decorating but also use it to support the conversation of a goal or the delivery of a message. Comments helps in gaining credibility and insights from users.

FIRST IMPRESSION LASTS

The world of websites is a world of first impression. A good design is important, even when the page is loading, or how the content is presented, users will judge it the minute they see your website. Take for instance adding a background image of woods, It gives the user a feeling of being at a relaxed and common place. It makes the user comfortable at the site and begins browsing around.

SET THE TONE RIGHT

We all know that in designing, every line spacing, typography used or even how elements are grouped are important in giving an impression to your users what your website is. For a professional theme using wrong typography like Comic Sans will ruin the look and feel of the site. Consistency is important. Just be sure that if you want to look different, be different.

USER REACTION

The web is so vast. Numerous sites and information is readily available in the web. The question is, how will your website outstand? Answer: Make your site reactive. Take advantage of social networking, share your site to your friends and let them leave comments in your site. The degreee of how viral your site will be depends on how the user feels and how easy it is to share.

UX design is about developing a road map for the user, encouraging certain actions, and developing a user base that wants to engage with your content. We make design to make the page more memorable and meaningful. We do this by laying a foundation of good impression by enabling smooth and meaningful reading and encouraging user engagement. This will make the user experience harmony in content.

Reference: The Role of Design in the Kingdom of Content

Monday, October 31, 2011

How to Add Syntax Highlighter in Blogger

I found this cool stuff called Syntax Highlighter by Alex Gorbatchev and uses it in my page. Basically, it highlights your code to have a nice color scheme.

How to install at blogger:
1. Go to Blogger Dashboard > Design > Edit HTML.
2. Press CTRL+F to find the </head> code
3. Copy the codes below:
4. Paste it on top of this </head> code
5. Preview your template, then if your code changes color, then save it.

For further details, you may click here and read more

Verdict
The good thing: It makes your codes more readable and it's easy to install.
The bad thing: It takes time to load your page because it gets its resources from Alex's site.

Wednesday, October 19, 2011

Basic Typography for reports

Last Tuesday, We had a design class. I learned something about cheats regarding making your reports. The instructor said that if you want to make your report look very presentable use 10 or 12 font-size because that is the font size that people are familiar with. Size 11 is like torn between two numbers so it wont be that effective.

In choosing your font face:
If all else fail, use Arial.


You ask why? There was a time that Times New Roman was said to be the most legible font face, but really it is Arial and it is the safest font to use for web interfaces. Also, If you want to make your report look studious, use the font face Helvetica. It has this feeling of being a book-like font.

For powerpoint presentations, add images after 3-4 slides and never forget to put a graph! Just make your presentation in bullet format. I remember the time back in High School where the students uses Cartolina just to have a visual presentation for the audience, now, powerpoint presentations are what's in!

With this simple things, you can create a great an impression that you are prepared and well-equipped even though you're not. Haha! I wish I had known this things while I was doing my book reports back in college.

Tuesday, October 18, 2011

Add ID to TR using Datatables

I find datatables for sorting of table very useful. (See datatables.net) It has live search and very flexible with customization. In my project, I tried to insert a new row by using the following sytax:
var myTable = $('#result_table').dataTable( );
var checkbox = 
var edit = Edit

$('#result_table').dataTable().fnAddData( [
     $('#add_division_name').val(),
     checkbox,
     edit
] );                          
But the problem is since the insertion is automated, I could not insert an ID for TR on the fly. So here's the solution I got:
// Get the settings of the table
var oSettings = $('#result_table').dataTable().fnSettings();       
// Count the rows, server side data
var rows = data.count;
// Insert the server side id
oSettings.aoData[rows].nTr.id = 'tr-' + data.id; 
I tried counting the hidden and shown rows so the counting of rows will be made front end by using the :hidden selector, but my codes doesn't seem to work. Looks like I have to stick to server side counting of rows.

Thursday, October 13, 2011

Passing data to jquery ui-dialog

I've always thought that passing of data to a dialog box in jquery is impossible. The only way to do this would mean setting a value to global variable and accessing it when ready. This post proves me wrong while browsing at stackoverflow.

jQuery provides a method which store data for you, no need to use a dummy attribute or to find workaround to your problem. Bind the click event:
$('a[href*=/Booking.aspx/Change]').bind('click', function(e) {
    e.preventDefault();
    $("#dialog-confirm")
        .data('link', this)  // The important part .data() method
        .dialog('open');
});
And your dialog:
$("#dialog-confirm").dialog({
    autoOpen: false,
    resizable: false,
    height:200,
    modal: true,
    buttons: {
        Cancel: function() {
            $(this).dialog('close');
        },
        'Delete': function() {
            $(this).dialog('close');
            var path = $(this).data('link').href; // Get the stored result
            $(location).attr('href', path);
        }
    }
});

Monday, October 10, 2011

My First Post

This is my first post.

Testing Post Outlook
"Knowledge without sharing is nothing"