My Google+ Profile

Tuesday, 16 July 2013

YII installation on xampp OS windows

Hello developers,

You have to follow following number of steps to create and run Yii application with XAMPP on windows machine.

1 : Install XAMPP. Click here to download XAMPP.

2 : Download Yii from community site. Rename to Yii and place it to xampp\htdocs folder.

3 : Set Environment variable for yii framework and php. (Right click on My computer and select properties -> Advance tab  -> Click on Environment variable button).

      Edit Path variable and add this two path.
            1) For Yii , C:\xampp\htdocs\yii\framework
            2) For PHP, C:\xampp\php

4 : Also edit xampp\htdocs\yii\framework\yii.bat file to enable yiic command to create yii application from command prompt(cmd).

        if "%PHP_COMMAND%" == "" set PHP_COMMAND=php.exe to  if "%PHP_COMMAND%" == "" set PHP_COMMAND=C:\xampp\php\php.exe

5 : Go the command prompt. Click on run and then type cmd. Command Prompt will open. Then change directory upto your  yii framework  folder.

      1 : cd C:\xampp\htdocs\yii\framework
      2 : yiic webapp yourapplicationname

Using all this step, you can create your Yii application on windows machine with XAMPP server.

Thanks,
Karmraj Zala.

Friday, 17 May 2013

Removing index.php from URL Yii

I am working with this configuration without any problem, make sure that your apache is set up correctly to allow mod_rewrite and htaccess files and ofcourse the mod_rewrite engine is on.

Config :


'urlManager' => array(

  'urlFormat' => 'path',

  'showScriptName' => false,
),
 
 
Create .htaccess file in Application directory.
  
.htaccess :
  
Options +FollowSymLinks
IndexIgnore */*

RewriteEngine on



# if a directory or a file exists, use it directly

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d



# otherwise forward it to index.php

RewriteRule . index.php 

Monday, 25 March 2013

How to Make Web Pages Load Faster

Including External scripts where there are same scripts on multiple pages:

It is always a good practice to add a external CSS & JS scripts with same path on multiple site pages as the scripts are stored in cache to make the loading faster.

Adding the heavy Java Scripts at the bottom

This is most noticeable easy & efficient way to reduce page loading time. Placing the java scripts just before </body> tag at the bottom of page loads the main content first & thus loading time is reduced significantly.

Clean up unnecessary codes & avoid duplicate scripts

Many times in hurry we include some scripts again & again or while designing we write a code for an id but we do not use that style. In such case avoiding these instances can decrease the loading time.
This is a best practice to load the style-sheets faster.

We find many designers just putting unnecessary efforts to make web pages flashy & heavy just to show they are out of box. But it often sidetracks the main motive of web page – to load fast & spread its message to readers. So it is always advisable to make a web page simple as possible to make it load faster & convey its message to its viewers.

Tuesday, 19 March 2013

include() vs require() on PHP

PHP provides four functions which enable you to insert code from other files.
* include()
* require()
* include_once()
* require_once()

All four can take a local file or URL as input. None of them can import a remote file.

require() and include() functions are virtually similar in their function except for the way they handle an irretrievable resource. include() and include_once() provide a warning if the resource cannot be retrieved and try to continue execution of the program if possible. require() and require_once functions provide stop processing the page if they cannot retrieve the resource.

Why include_once() and require_once() ?

The include_once() and require_once() functions are handy in situations where multiple files may reference the same included code.

For example:

File A.php includes File B.php and C.php
File B.php includes File C.php

File C.php has been included twice, so the interpreter would print an error. Since a function cannot be redefined once it’s declared, this restriction can help prevent errors.

If both File A.php and File B.php use include_once() or require_once() to import File C.php, no errors would be generated. PHP would understand that you only want one instance of the code in File C and would not try to redeclare the functions.

It is best to use require_once() to include files which contain necessary code and include_once() to include files that contain content which the program can run without e.g. HTML, CSS, etc.

Wednesday, 13 March 2013

PHP Array Functions

Array is a Most useful Data Storage in Most of the Programming Languages   Some of unknown array build in functions in php.
                                PHP Array Functions

array_diff (arr1, arr2 …)

array_­filter (arr, function)

array_flip (arr)

array_­int­ersect (arr1, arr2 …)

array_­merge (arr1, arr2 …)

array_pop (arr)

array_push (arr, var1, var2 …)

array_­reverse (arr)

array_­search (needle, arr)

array_walk (arr, function)

count (count)

in_array (needle, haystack)

Yii – adding JavaScript into your views using Controller

We can use Yii’s CClientScript for add javascript.
//in your view where you want to include JavaScripts  
Add following line of code in your controller action :  
$cs = Yii::app()->getClientScript();  
$cs->registerScript(
  'my-hello-world-1',
  'var popup = "Hello" + " " + "World";
  alert(popup);',
  CClientScript::POS_END
);
In the example above, the first argument is an ID uniquely identifies the script, the second is the actual JavaScript. The third argument determinds where the JavaScript will be inserted into the view – by using CClientScript::POS_END the script will be inserted at the before the closing of the body tag.

If you wish to include a JavaScript file instead, we can use registerScriptFile.
First, we place our JavaScript into protected/components/js folder.

Add following line in  controller  action.
Yii::app()->clientScript->registerScriptFile(
        Yii::app()->baseUrl . '/components/js/myScript.js',
 CClientScript::POS_END
 );

Friday, 1 March 2013

HTML5 forms introduction and new attributes

HTML5 form attributes

There are 14 new attributes that we’ll be looking at in this article.

placeholder

First up is the placeholder attribute, which allows us to set placeholder text as we would currently do in HTML4 with the value attribute. It should only be used for short descriptions. For anything longer, use the title attribute. The difference from HTML4 is that the text is only displayed when the field is empty and hasn’t received focus. Once the field receives focus (e.g., you click or tab to the field), and you begin to type, the text simply disappears. It’s very similar to the search box you see in Safari (see Figure 1).
Screenshot of the browser search box in Safari with and without focus
Figure 1. Browser search box in Safari without and with focus
Let’s have a look at how to implement the placeholder attribute.

<input type="text" name="user-name" id="user-name"  
placeholder="at least 3 characters">
 
That’s it! We can hear you thinking, “What’s so great about that? I’ve been doing it with JavaScript for years.” Yes, that’s true. However, with HTML5, it’s part of the browser, meaning less scripting is required for a more accessible, cross-browser solution (even when JavaScript is disabled). Figure 2 shows the placeholder attribute working in Chrome.
Screenshot of an input field in Chrome with and without focus, so showing and not showing the placeholder
Figure 2. Placeholder attribute support in Chrome, unfocused and focused
Browsers that don’t support the placeholder attribute ignore it, so it won’t render. By including it, though, you’re providing an enhanced user experience for those users who have browser support and you’re “future proofing” your site. All modern browsers support placeholder.
Note: There is no official pseudo-class for styling placeholder text but both Mozilla (makers of Firefox) and WebKit offer vendor prefixed properties for styling (-mozplaceholder and –webkit-input-placeholder). This makes it safe to assume that a pseudo-class will become standard for styling placeholder text. For further detail there is a thread on the WHATWG mailing list about this topic.

autofocus

autofocus does exactly what it says on the tin. Adding it to an input automatically focuses that field when the page is rendered. As with placeholder, autofocus is something that we used JavaScript for in the past.
Traditional JavaScript methods do, though, have some serious usability problems. For example, if a user begins completing the form before the script loads, they will (jarringly) be returned to the first form field when the script is loaded. The autofocus attribute in HTML5 gets around this issue by focusing as soon as the document loads, without having to wait for the JavaScript to be loaded. However, we only recommend using it for pages whose sole purpose is the form (like Google) to prevent the usability issues.
It is a Boolean attribute (except if you are writing XHTML5; see the note) and is implemented as follows:

<input type="text" name="first-name" id="first-name" autofocus>
All modern browsers support the attribute and, like placeholder, browsers that don’t support the autofocus attribute simply ignore it.
Note: Several new HTML5 form attributes are Boolean attributes. This just means they’re set if they’re present and not set if they’re absent. They can be written several ways in HTML5.
autofocus
autofocus=""
autofocus="autofocus"
However, if you are writing XHTML5, you have to use the autofocus="autofocus" style.

autocomplete

The autocomplete attribute helps users complete forms based on earlier input. The attribute has been around since IE5.5 but has finally been standardized as part of HTML5. The default state is set to on. This means that generally we won’t have to use it. However, if you want to insist that a form field be entered each time a form is completed (as opposed to the browser autofilling the field), you would implement it like so:
<input type="text" name="tracking-code" id="tracking-code" autocomplete="off">
The autocomplete state on a field overrides any autocomplete state set on the containing form element.

required

The required attribute doesn’t need much introduction; like autofocus, it does exactly what you’d expect. By adding it to a form field, the browser requires the user to enter data into that field before submitting the form. This replaces the basic form validation currently implemented with JavaScript, making things a little more usable and saving us a little more development time. required is a Boolean attribute, like autofocus. Let’s see it in action.
<input type="text" id="given-name" name="given-name" required>
required is currently implemented only in Opera 9.5+, Firefox 4+, Safari 5+, Internet Explorer 10 and Chrome 5+, so for the time being you need to continue writing a script to check that fields are completed on the client side in other browsers (*cough* IE!). Opera, Chrome, and Firefox show the user an error message (see Figure 3) upon form submission. In most browsers, the errors are then localized based on the declared language. Safari doesn’t show an error message on submit, but instead places focus on that field.
Screenshot from Opera showing an error message on an input field
Figure 3. Form field with required attribute displaying a browser-generated error message in Opera
The default rendering of “required” error messages depends on the individual browser; at present the error message bubble can’t be styled with CSS in all browsers. Chrome, however, does have a proprietary property that you can use to style the error bubble. Peter Gasston has written an article about the syntax. You can also style the input using the :required pseudo-class. An alternative is to override the wording and styling using the setCustomValidity() method in JavaScript. Importantly, don’t forget that this browser validation is no substitute for validating on the server as well.

pattern

The pattern attribute is likely to get a lot of developers very excited (well, as excited as you can get about form attributes). It specifies a JavaScript regular expression for the field’s value to be checked against. pattern makes it easy for us to implement specific validation for product codes, invoice numbers, and so on. The possibilities for pattern are wide-ranging, and this is just one simple example using a product number.

<label>Product Number:<input pattern="[0-9][A-Z]{3}" name="product" 
 type="text" title="Single digit followed by three uppercase letters."/>
</label>
 
This pattern prescribes that the product number should be a single digit [0-9] followed by three uppercase letters [A-Z]{3}. For more examples, the HTML5 Pattern website lists common regex style patterns to help get you started.
As with required, Opera 9.5+, Firefox 4+, Safari 5+, Internet Explorer 10 and Chrome 5+ are the only browsers with support for pattern at present. However, with the browser market moving at a fast pace, the others will soon catch up.

list and the datalist element

The list attribute enables the user to associate a list of options with a particular field. The value of the list attribute must be the same as the ID of a datalist element that resides in the same document. The datalist element is new in HTML5 and represents a predefined list of options for form controls. It works in a similar way to the in-browser search boxes that autocomplete as you type (see Figure 4).
Screenshot Google's autosuggest functionality in Safaris search box
Figure 4. Google search autosuggestions in Safari
The following example shows how list and datalist are combined (see Figure 5):
<label>Your favorite fruit:<datalist id="fruits">
  <option value="Blackberry">Blackberry</option>
  <option value="Blackcurrant">Blackcurrant</option>
  <option value="Blueberry">Blueberry</option>
  <!-- … -->
</datalist>
If other, please specify:
  <input type="text" name="fruit" list="fruits">
</label>
By adding a select element inside the datalist you can provide superior graceful degradation than by simply using an option element. This is an elegant markup pattern designed by Jeremy Keith that adheres perfectly with HTML5′s principle of degrading gracefully.
<label>Your favorite fruit:<datalist id="fruits">
  <select name="fruits">
    <option value="Blackberry">Blackberry</option>
    <option value="Blackcurrant">Blackcurrant</option>
    <option value="Blueberry">Blueberry</option>
    <!-- … -->
  </select>
If other, please specify:</datalist>
  <input type="text" name="fruit" list="fruits">
</label>
Browser support for list and datalist is currently limited to Opera 9.5+ (see Figure 5), Chrome 20+, Internet Explorer 10 and Firefox 4+.
Screenshot of the list attribute and datalist element in Opera
Figure 5. The datalist element rendered in Opera

multiple

We can take our lists and datalists one step further by applying the Boolean attribute multiple to allow more than one value to be entered from the datalist. Here is an example.

<label>Your favorite fruit:<datalist id="fruits">
  <select name="fruits">
    <option value="Blackberry">Blackberry</option>
    <option value="Blackcurrant">Blackcurrant</option>
    <option value="Blueberry">Blueberry</option>
    <!-- … -->
  </select>
If other, please specify:</datalist>
  <input type="text" name="fruit" list="fruits" multiple>
</label>
 
multiple isn’t exclusively for use with datalists, though. A further example for multiple might be for email addresses when sending items to friend or the attachment of files, as shown here:

<label>Upload files:<input type="file" multiple name="upload"></label>
 
multiple is supported in Firefox 3.6+, Safari 4+, Opera 11.5+, Internet Explorer 10 and Chrome 4+.

novalidate and formnovalidate

The novalidate and formnovalidate attributes indicate that the form shouldn’t be validated when submitted. They are both Boolean attributes. formnovalidate can be applied to submit or image input types. The novalidate attribute can be set only on the form element.
An example use case for the formnovalidate attribute could be on a “save draft” button, where the form has fields that are required for submitting the draft but aren’t required for saving the draft. novalidate would be used in cases where you don’t want to validate the form but do want to take advantage of the more useful user interface enhancements that the new input types offer.
The following example shows how to use formnovalidate:
<form action="process.php">
  <label for="email">Email:</label>
  <input type="text" name="email" value="gordo@example.com">
  <input type="submit" formnovalidate value="Submit">
</form>
And this example shows how to use novalidate:
<form action="process.php" novalidate>
  <label for="email">Email:</label>
  <input type="text" name="email" value="gordo@example.com">
  <input type="submit" value="Submit">
</form>

form

The form attribute is used to associate an input, select, or textarea element with a form (known as its form owner). Using form means that the element doesn’t need to be a child of the associated form and can be moved away from it in the source. The primary use case for this is that input buttons that are placed within tables can now be associated with a form.
<input type="button" name="sort-l-h" form="sort">

formaction, formenctype, formmethod, and formtarget

The formaction, formenctype, formmethod, and formtarget attributes each have a corresponding attribute on the form element, which you’ll be familiar with from HTML4, so let’s run through each of them briefly. These new attributes have been introduced primarily because you may require alternative actions for different submit buttons, as opposed to having several forms in a document.

formaction

formaction specifies the file or application that will submit the form. It has the same effect as the action attribute on the form element and can only be used with a submit or image button (type="submit" or type="image"). When the form is submitted, the browser first checks for a formaction attribute; if that isn’t present, it proceeds to look for an action attribute on the form.
<input type="submit" value="Submit" formaction="process.php">

formenctype

formenctype details how the form data is encoded with the POST method type. It has the same effect as the enctype attribute on the form element and can only be used with a submit or image button (type="submit" or type="image"). The default value if not included is application/x-www-formurlencoded.
<input type="submit" value="Submit" formenctype="application/x-www-form-urlencoded">

formmethod

formmethod specifies which HTTP method (GET, POST, PUT, DELETE) will be used to submit the form data. It has the same effect as the method attribute on the form element and can only be used with a submit or image button (type="submit" or type="image").
<input type="submit" value="Submit" formmethod="POST">

formtarget

formtarget specifies the target window for the form results. It has the same effect as the target attribute on the form element and can only be used with a submit or image button (type="submit" or type="image").
<input type="submit" value="Submit" formtarget="_self">

Tuesday, 15 January 2013

Best MVC Practices

Although Model-View-Controller (MVC) is known by nearly every Web developer, how to properly use MVC in real application development still eludes many people. The central idea behind MVC is code reusability and separation of concerns. In this section, we describe some general guidelines on how to better follow MVC when developing a Yii application.
To better explain these guidelines, we assume a Web application consists of several sub-applications, such as
  • front end: a public-facing website for normal end users;
  • back end: a website that exposes administrative functionality for managing the application. This is usually restricted to administrative staff;
  • console: an application consisting of console commands to be run in a terminal window or as scheduled jobs to support the whole application;
  • Web API: providing interfaces to third parties for integrating with the application.
The sub-applications may be implemented in terms of modules, or as a Yii application that shares some code with other sub-applications.

1. Model

Models represent the underlying data structure of a Web application. Models are often shared among different sub-applications of a Web application. For example, a LoginForm model may be used by both the front end and the back end of an application; a News model may be used by the console commands, Web APIs, and the front/back end of an application. Therefore, models
  • should contain properties to represent specific data;
  • should contain business logic (e.g. validation rules) to ensure the represented data fulfills the design requirement;
  • may contain code for manipulating data. For example, a SearchForm model, besides representing the search input data, may contain a search method to implement the actual search.
Sometimes, following the last rule above may make a model very fat, containing too much code in a single class. It may also make the model hard to maintain if the code it contains serves different purposes. For example, a News model may contain a method named getLatestNews which is only used by the front end; it may also contain a method named getDeletedNews which is only used by the back end. This may be fine for an application of small to medium size. For large applications, the following strategy may be used to make models more maintainable:
  • Define a NewsBase model class which only contains code shared by different sub-applications (e.g. front end, back end);
  • In each sub-application, define a News model by extending from NewsBase. Place all of the code that is specific to the sub-application in this News model.
So, if we were to employ this strategy in our above example, we would add a News model in the front end application that contains only the getLatestNews method, and we would add another News model in the back end application, which contains only the getDeletedNews method.
In general, models should not contain logic that deals directly with end users. More specifically, models
  • should not use $_GET, $_POST, or other similar variables that are directly tied to the end-user request. Remember that a model may be used by a totally different sub-application (e.g. unit test, Web API) that may not use these variables to represent user requests. These variables pertaining to the user request should be handled by the Controller.
  • should avoid embedding HTML or other presentational code. Because presentational code varies according to end user requirements (e.g. front end and back end may show the detail of a news in completely different formats), it is better taken care of by views.

2. View

Views are responsible for presenting models in the format that end users desire. In general, views
  • should mainly contain presentational code, such as HTML, and simple PHP code to traverse, format and render data;
  • should avoid containing code that performs explicit DB queries. Such code is better placed in models.
  • should avoid direct access to $_GET, $_POST, or other similar variables that represent the end user request. This is the controller's job. The view should be focused on the display and layout of the data provided to it by the controller and/or model, but not attempting to access request variables or the database directly.
  • may access properties and methods of controllers and models directly. However, this should be done only for the purpose of presentation.
Views can be reused in different ways:
  • Layout: common presentational areas (e.g. page header, footer) can be put in a layout view.
  • Partial views: use partial views (views that are not decorated by layouts) to reuse fragments of presentational code. For example, we use _form.php partial view to render the model input form that is used in both model creation and updating pages.
  • Widgets: if a lot of logic is needed to present a partial view, the partial view can be turned into a widget whose class file is the best place to contain this logic. For widgets that generate a lot of HTML markup, it is best to use view files specific to the widget to contain the markup.
  • Helper classes: in views we often need some code snippets to do tiny tasks such as formatting data or generating HTML tags. Rather than placing this code directly into the view files, a better approach is to place all of these code snippets in a view helper class. Then, just use the helper class in your view files. Yii provides an example of this approach. Yii has a powerful CHtml helper class that can produce commonly used HTML code. Helper classes may be put in an autoloadable directory so that they can be used without explicit class inclusion.

3. Controller

Controllers are the glue that binds models, views and other components together into a runnable application. Controllers are responsible for dealing directly with end user requests. Therefore, controllers
  • may access $_GET, $_POST and other PHP variables that represent user requests;
  • may create model instances and manage their life cycles. For example, in a typical model update action, the controller may first create the model instance; then populate the model with the user input from $_POST; after saving the model successfully, the controller may redirect the user browser to the model detail page. Note that the actual implementation of saving a model should be located in the model instead of the controller.
  • should avoid containing embedded SQL statements, which are better kept in models.
  • should avoid containing any HTML or any other presentational markup. This is better kept in views.
In a well-designed MVC application, controllers are often very thin, containing probably only a few dozen lines of code; while models are very fat, containing most of the code responsible for representing and manipulating the data. This is because the data structure and business logic represented by models is typically very specific to the particular application, and needs to be heavily customized to meet the specific application requirements; while controller logic often follows a similar pattern across applications and therefore may well be simplified by the underlying framework or the base classes.

Thursday, 3 January 2013

Benefits and Advantages of HTML5 Semantic Markup for SEO



Why Should Developers Be Excited About Semantic Markup?

Semantic Markup is best defined as using special HTML tags that describe what kind of content it contains. In very simple terms: it offers you very clean code – something all SEOs and developers love.
To illustrate the advantages that HTML5 offers, consider how <h1> and <p> elements are used to differentiate separate kinds of text on a page. These <h1> & <h2> tags are critical to on-page SEO. They are on the top of the HTML markup food chain and theoretically should describe the current pages topic.
HTML5 takes semantics a step further with new HTML tags for larger portions of websites. Take a look at some of them below:

<header></header>
<nav></nav>
<menu></menu>
<article></article>
<section></section>
<aside></aside>
<footer></footer>
 
Most likely you can guess what some of the above tags should be used for on a web page.

If not, here is a very brief breakdown:

The <header> Element

The header element is used to contain the header elements of any block of related content. For example, the global header for a website that contains a sites logo and or navigation would be a basic example of where to use this tag.The <footer> Element
This element is used in the same way as the header element but for common footer elements of a block of related content. An example of this would be the utility links on the footer of a site.

The <nav> Element

This one is fairly simple but it can also be abused. This is intended to define major navigation areas on a page, and in most cases, will be groups of links. Be aware that just because several links might be in proximity of each other does not qualify the use of the <nav> element.

The <menu> Element

This element is similar to the <nav> element but is a more relaxed fashion. This element might be used to group together links that act as a sub-navigation. Another user would be for social media icons that link out to a site’s social media pages.

The <article> Element

This element is used for self-contained compositions of a webpage. For example, a list of your site’s blog posts each would be contained by an <article> tag. This can also be used for other types of content as well. Just keep in mind its self-contained use.

The <section> Element

The <section> element is commonly misused. Most people would think of using the section tag as a container block level element to contain a portion of the site. This is incorrect. The true way to use the section element is to think of it in terms of grouping specific portions of content. Inside a section you may have multiple headings to further narrow the focus of the section and there may be multiple sections inside a particular piece of content. Whew! If you find yourself confused by this (I know I was originally) then don’t worry. You can check out this article by Bruce Lawson for a more in-depth view of the section element : Prognosis of the HTML5 Section Element.

The <aside> Element

This is another frequently misused element. Most people think of this element as a sidebar container. A better way of understanding of how to use the <aside> element is by reserving it for tangentially related content outside of an article. One way you may use it is when you have a sidebar element that contains features a block of advertisement above a blogroll panel. The blogroll is tangentially related to the blog article but the advertisement block is not related to the article tangentially. Therefore, using an <aside> tag for an entire sidebar doesn’t accurately describe its contents.

So What’s the Big Deal for SEO?

This is not only easy for us to understand but also much easier for a Google Bot to crawl and index due to its clean markup. Traditional methods for defining header and footer containers consisted of <div> tags with unique id’s to target them with CSS for styling. While that is an effective way of doing things it is far messier than using specific tags for each area of content.

Look at the example below of how many current websites use <div> tags to create a basic two-column layout with a header and footer:

<div id=”header”>
<ul id=”nav”>
</ul><!-- End #nav -->
</div><!-- End #header -->
<div id=”content”>
<div id="blogpost">
<h1>This is my Blogpost</h1>
<p>This is my first paragraph.</p>
</div><!-- End #blogpost -->
</div><!-- End #content -->
<div id=”sidebar”>
<div id="blogroll">
<p>My blogroll Content.</p>
</div><!-- End #blogroll -->
</div><!-- End #sidebar -->
<div id=”footer”>
<p>My Footer Content.</p>
</div><!-- End #footer --> 

And below is the same layout using HTML5 markup:

<header> <nav></nav> </header>
<div id=”content”>
<article id="blogpost">
<section> <h1>This is my Blogpost</h1>
<p>This is my first paragraph.</p>
</section> </article><!-- End #blogpost --> </div><!-- End #content -->
<div id=”sidebar”> <aside id="blogroll"> <p>My blogroll Content.</p> </aside>
<!-- End #blogroll --> </div><!-- End #sidebar --> <footer> <p>My Footer Content.</p> </footer>

While the markup might not seem shorter it definitely is more semantic. The <div> elements in the first example have no semantic meaning outside their given ID attributes. Whereas, the second example uses the new semantic markup HTML5 elements to better describe the content and the overall layout of the page. This will be much easily understood by a Google Bot or a screen reader due to its logical markup.

And of Course…. The Drawbacks

Unfortunately, do to the lack of standardization between browsers currently these tags can be interpreted differently or entirely ignored all together. This most commonly happens in older versions of Internet Explorer. Luckily, there are methods to “teach” the browser what these new tags are in order to style them appropriately using CSS. Simply embed this script in the <head> section of your markup to enable the use of the new tags for older browsers:

<!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]-->

Without getting too technical, when the above jQuery script runs it creates new elements inside the Internet Explorer Document Object Model(DOM) so that it understands the new markup. Bottom line is that it works and that is all that matters to most people. The only qualm some people have regarding the above patch is that it is JavaScript dependent. However, the percentage of users who browse with JavaScript disabled has been on the decline for several years and is a very small portion of the overall users on the web.

Wednesday, 2 January 2013

MVC vs. MVP vs. MVVM


MVC: Three components – View (your UI), Model (your business entities / data – that view is displaying) & Controller (contains the logic that alters the model depending on the action triggered by UI, typically implementing a Use Case). It’s widely known that MVC is a compound pattern (View and Controller have Strategy implementation, View itself can be a Composite implementation & View and Model are synched through Observer). In this case Controller doesn’t know anything about View, and the idea is that a View can switch Controllers (for instance depending upon who has logged to the system) & a single controller can be used by multiple Views. View subscribes to the changes done to the model & hence both are sync from the data perspective. One of the disadvantages of MVC is that it’s difficult to unit test. Controller manipulates the data but how about asserting those changes from a view perspective. For instance on click of a button you raise an event to controller, and controller modifies the value in model. This value modification changes the font size / color in View. Unit testing this scenario is slightly difficult in MVC.

MVP: Again three components. But dependencies change (look at arrows in the diagram). Over here we replace Controller with Presenter (one which presents the changes done in model back to view). The main difference between both is that Presenter refers back to the view while Controller doesn’t. Normal pattern found here is to create an abstraction of the View (in terms of properties / events) & Presenter refers to it. This makes the mocking of View much easier & hence the Unit Testing aspect. Presenter here hence takes the responsibility of not only manipulating model but also updating the view. Of course the implementations of MVP differ in real world in terms of how much thin the view is, some prefer keeping basic logic still inside view & taking complex logic in presenter, while others prefer keeping the entire logic in Presenter. Martin fowler describes 2 variations on MVP on these lines namely – Supervising Controller & Passive View described below
(A Passive View handles this by reducing the behavior of the UI components to the absolute minimum by using a controller that not just handles responses to user events, but also does all the updating of the view. This allows testing to be focused on the controller with little risk of problems in the view.
Supervising Controller uses a controller both to handle input response but also to manipulate the view to handle more complex view logic. It leaves simple view behavior to the declarative system, intervening only when effects are needed that are beyond what can be achieved declaratively.)

MVVM: Model–View-ViewModel talks of creating a new model (in addition to your domain model). This model normally adds additonal properties from the prespective of View (as we understand that View has controls in addition to data which it’s displaying). For instance if View had a property IsChecked and Presenter was setting in classic MVP, in MVVM Presenter will have that IsChecked Property which View will sync up with (doesn’t it look like Strategy pattern has been replaced with Observer?). So now a Presenter becomes more like a combo of – View Properties & Model properties which would be synchronized with View. So why not rename Presenter to ViewModel? Do that and you get MVVM. MVVM is attractive for platforms which support bi-directional binding with less effort.


Friday, 28 December 2012

Why Yii Framework become more Popularity?

What is new feature of Yii? Why is it becoming so popular among developers today?

Yii (acronym for ‘Yes It Is!’) is a component-based PHP framework with high performance level that best fits for developing Web applications of large scale. Yii comes with a full pack of features covering DAO/ActiveRecord, MVC, caching, I18N/L10N, jQuery-based AJAX support, authentication and role-based access control, input validation, scaffolding, events, widgets, Web services, theming etc.

Yii was created for web programming of general purpose which can be used for development of basically any sort of web applications. Thanks to the presence of the powerful caching tool, Yii is particularly effective for rapid applications development with a big traffic flow such as forums, CMS, portals, eCommerce systems etc. It is known for its flexibility, usability and high speed. Among its other advantages Yii supports modules, components and widgets as well as integrates with JavaScript framework jQuery. It can also be utilized either as Active Record or as Data Access Objects. In addition Yii has a convenient web-based code generator called Gii and there is a command line interface for some operations like DB migrations.

Yii is written using OOP principles and therefore it is very flexible and extensive as well as it is easy to use. Yii has a large community and as a result a lot of solutions in the form of extensions. There is good support with an ability to offer changes and improvements on Github. Moreover, Yii has publicly available excellent documentation.

Many developers, after having dealt with Yii are left totally impressed by the framework. Lots of them agree that the learning curve is pretty short thanks to its ability to eliminate duplicating code and automatic adapting to the database changes. Security issues are also taken care of due to the input validation functionality of CModel and the usage of PDO and parameter binding by CActive Record and making the operations safe by default.

You can see the comparison at http://www.phpframeworks.com/top-10-php-frameworks with other popular frameworks, Yii holds the highest positions.

Friday, 21 December 2012

Multi-language site in yii framework

To make multi language in your yii framework you have to implements some rules. You can use the session variables to make the translation between your page. With the the documentation you can look at here.

I have to implements this to make the translation page. You can follow the instruction in that articles that not almost I discuss in this page.

But when I finish implement that step, I can make my own translation page on the protected/messages/<your language id>/<your category>.php files..

For the example :

../protected/messages/id/translation.php

The example of the translation page that I use like this

<?php
/**
 * Indonesian translate
 */
return array(
  //------MENU------------//
  'Home'=>'Beranda',
  'About'=>'Tentang',
  'Contact'=>'Kontak',
  'Login'=>'Masuk',
  'Logout'=>'Keluar',
   
   
   
  //----------- Other Example ------------------//
  'What are You Looking For?'=>'Apa Yang Anda Cari?',
  'Sell Your Products'=>'Mau Menjual Barang',
  'Products'=>'Barang',
  'Services'=>'Jasa'
   
  );
?>


Oke when you finish that I use my native languages (Indonesian=ID) and than I can use that for my translation in my code using this example in your view files.

echo Yii::t('translation','Home');

Wednesday, 19 December 2012

Drupal 7 - The basic way of using the Colorbox module

This article is about the usage of Jquery Colorbox Plugin, which most of you must be either accustomed to or at least heard of. This post is aimed at those who know about the module, but still haven’t made the use of it. So, here’s what to begin with.

The Colorbox module is a light-weight as well as customizable lightbox plugin for jQuery 1.3 through 1.6. When it comes to Drupal 7, the colorbox jquery plugin is integrated with a module Colorbox. The usage of this module facilitates the display of images, iframed or inline content etc. in an overlay above the current page.

Features of the Colorbox module

Let’s take a brief look at the various features of the Colorbox module. The following are a list of its features:
  1. Outstanding integration with Imagefield Imagecache, Insert and  Image modules.
  2. A variety of choice is available between a default style and a number of other styles that are included.
  3. The facility of styling the Colorbox with a custom Colorbox style in your theme is also present.
  4. There’s an option to open a login form by clicking on any login link
  5. Drush command is available to download and install the Colorbox plugin in sites/all/libraries as well as a Drush make file

Features of the Colorbox plugin:

  • Supports images, image groups, slideshow, ajax, inline, and iframed content.
  • Preloads background images and can preload upcoming images in a photo group.
  • Appearance is controlled through CSS so users can restyle the box.

Showing content images in Colorbox

Having discussed the features of the module, let’s move on to make use of the Colorbox module in order to show content images in a colorbox.

Step: 1

Download the Colorbox module from drupal.org and place it in sites/all/modules folder.

Step: 2

Now, go to modules and then enable the Colorbox module.

Step: 3

Download and unpack the Colorbox plugin in “sites/all/libraries”.
Link: http://colorpowered.com/colorbox/colorbox.zip
The Drush users can use the command “drush colorbox-plugin”.

Step: 4 

You’ll have to add 2 new presets by clicking on configuration-> Media ->Image Styles.
Set the height and width of the presets according to your requirements.
While one preset will be used for the purpose of preview image, the other one will be use for the full image to be shown on colorbox.
Save both the image styles.

Step: 5

Now, create a new content type, and then add an image field to it.
Select the image preview style name we just created in the image styles. Here we will use the smaller image to be shown on the listing page. Click on the save option.
Add some images to the new content type we just created.

Step: 6

After this, create a view and give it a name and continue with the default settings.
Apply the filter criteria by choosing the content name as the filter.
Now select fields to display in the view.

Step: 7

Select Content Title and Content : Image Field Name as the fields.
In the Image Field Name settings page enter a label name for the field.

Step: 8

Now, from the Formatter dropdown select the Colorbox option.
In the Node Image Style choose the name of the image style we created. Remember to use the smaller size for this field.

Step: 9

In the Colorbox Image Style select the name of bigger image style.
Click save and save the views also.

Step: 10

Here, go back to the content type we have just created and then,

Click on Manage Display Field.

Next to Image field you’ll be able to notice a dropdown menu labeled as Format.

Select Colorbox and configure the settings for the field.
 
Node Image Style: Smaller Image style.
Colorbox Image Stye: Large Image Style.

All done, now click on Save.

After following all the above mentioned steps, you should be able to see your images in a colorbox by clicking on them.

You can also choose to use the Colorbox Stylesheets. All you have to do is to simply copy the whole folder into your theme folder and then include it into your template files.

The Colorbox plugin is very useful and we can do a lot of things with the images with the help of this module. Hope we were able to deliver the idea of the basic stuff to begin with through this post.

Sunday, 16 December 2012

8 Tips for Drupal Usability

Usability is not a big problem to talk a lot about it in the Drupal community. But it makes Drupal services more comfortable for users and we still try to make Drupal sites as usable as possible. Fortunately there are a lot of simply tools you can use to make your life easier.
Let’s give you some simple tips how to improve the usability of Drupal.

Build your own admin dashboard

There are a lot of experimental modules to build it. You may have Wordpress like a dashboard screen for admin. Using Panels can be very useful.

Many users don’t understand multiple select boxes

Probably most of the people know that in order to select multiple options in a select box you may use Ctrl+Click. But many people do not aware of it. They think it is rather to use checkboxes instead.

Disable all distractions which the user doesn’t need

Of course, Drupal provides a lot of useful functions but don’t give to your visitors the information which is not useful for them.

Show the results

Drupal doesn’t automatically display the number of search results. But you can add this functionality to make a big help for your visitors.

Make your node-edit screen

In order to make your node-edit screen more usable you can use Drupal 6 module. Then vertical tabs will make your node edit screen less cluttered.

Redirect visitors to the right place

You need to separate admin roles and task for administrators to send users directly to the specific page. In order to do it you can use Rules or the core trigger module. The last one has more features.

Use Diff module to see the differences are made

Diff module is pretty useful with revision option for nodes. So you can use it to see any changing is made.

Taxonomy

Taxonomy can be a little confused for some users. You may have hierarchical select steps in as an option and it could automatically control it. Also it enables selection methods through jQuery to find a lot of scalable solutions.

Monday, 10 December 2012

Tree structure in Dropdown using Yii

In this tutorial, we create tree structure dropdown list like as below :-

RHCE
--SE1
RHCSA
--SA1
--SA2
PHP

Table strucure for this kind of tree is as below :
id parent_id course_name
1     0               RHCE
2     0               RHCSA
3     1               SE1
4     2               SA1
5     2              SA2
6     0              PHP

I have create class file in component folder because i can use it anywhere in my application but you can create this file's function anywhere.

In components folder create a new class CommonMethods.

<?php
/*
* /protected/components/CommonMethods.php

 */
class CommonMethods {
 
    private $data = array();
   
    public function makeDropDown($parents)
    {
        global $data;
        $data = array();
        $data['0'] = '-- ROOT --';
        foreach($parents as $parent)
        {
           
                $data[$parent->id] = $parent->name;
                $this->subDropDown($parent->children);
               
        }
       
       return $data;
    }
   
  public function subDropDown($children,$space = '---')
    {
        global $data;
       
        foreach($children as $child)
                {
                   
                        $data[$child->id] = $space.$child->name;
                        $this->subDropDown($child->children,$space.'---');
                }
       
    }
   
   
}
?>

In you model make relations.
public function relations()
{
                  return array(

                    'parent' => array(self::BELONGS_TO, 'CourseMaster', 'parent_id', 'condition' => 't.parent_id <> 0'),

                    'children' => array(self::HAS_MANY, 'CourseMaster', 'parent_id'),

               );

}

In your view _form.php
    <div class="row">

       <?php


          $parents = CourseMaster::model()->findAll('parent_id = 0');
 $cm = new CommonMethods();

          $data = $cm->makeDropDown($parents);


          echo $form->labelEx($model,'parent_id');

          echo $form->dropDownList($model,'parent_id',  $data);


      ?>


    </div>

Thursday, 6 December 2012

PHP mysql_real_escape_string() Function to prevent MySQL - SQL Injection Prevention

What is SQL Injection

SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

SQL Injection Example

Below is a sample string that has been gathered from a normal user and a bad user trying to use SQL Injection. We asked the users for their login, which will be used to run a SELECT statement to get their information.

MySQL & PHP Code:

// a good user's name
$name = "timmy"; 
$query = "SELECT * FROM customers WHERE username = '$name'";
echo "Normal: " . $query . "<br />";

// user input that uses SQL Injection
$name_bad = "' OR 1'"; 

// our MySQL query builder, however, not a very safe one
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";

// display what the new query will look like, with injection
echo "Injection: " . $query_bad;

Display:

Normal: SELECT * FROM customers WHERE username = 'timmy'
Injection: SELECT * FROM customers WHERE username = '' OR 1''



The normal query is no problem, as our MySQL statement will just select everything from customers that has a username equal to timmy.
However, the injection attack has actually made our query behave differently than we intended. By using a single quote (') they have ended the string part of our MySQL query
  • username = ' '
and then added on to our WHERE statement with an OR clause of 1 (always true).
  • username = ' ' OR 1
This OR clause of 1 will always be true and so every single entry in the "customers" table would be selected by this statement!


More Serious SQL Injection Attacks


Although the above example displayed a situation where an attacker could possibly get access to a lot of information they shouldn't have, the attacks can be a lot worse. For example an attacker could empty out a table by executing a DELETE statement.

MySQL & PHP Code:

$name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; 

// our MySQL query builder really should check for injection
$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";

// the new evil injection query would include a DELETE statement
echo "Injection: " . $query_evil;

Display:

SELECT * FROM customers WHERE username = ' '; DELETE FROM customers WHERE 1 or username = ' ' 

If you were run this query, then the injected DELETE statement would completely empty your "customers" table. Now that you know this is a problem, how can you prevent it?

Injection Prevention - mysql_real_escape_string()

Lucky for you, this problem has been known for a while and PHP has a specially-made function to prevent these attacks. All you need to do is use the mouthful of a function mysql_real_escape_string.
What mysql_real_escape_string does is take a string that is going to be used in a MySQL query and return the same string with all SQL Injection attempts safely escaped. Basically, it will replace those troublesome quotes(') a user might enter with a MySQL-safe substitute, an escaped quote \'.
Lets try out this function on our two previous injection attacks and see how it works.

MySQL & PHP Code:

//NOTE: you must be connected to the database to use this function!
// connect to MySQL

$name_bad = "' OR 1'"; 

$name_bad = mysql_real_escape_string($name_bad);

$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";
echo "Escaped Bad Injection: <br />" . $query_bad . "<br />";


$name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; 

$name_evil = mysql_real_escape_string($name_evil);

$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";
echo "Escaped Evil Injection: <br />" . $query_evil;

Display:

Escaped Bad Injection:
SELECT * FROM customers WHERE username = '\' OR 1\''

Escaped Evil Injection:
SELECT * FROM customers WHERE username = '\'; DELETE FROM customers WHERE 1 or username = \''

Notice that those evil quotes have been escaped with a backslash \, preventing the injection attack. Now all these queries will do is try to find a username that is just completely ridiculous:
  • Bad: \' OR 1\'
  • Evil: \'; DELETE FROM customers WHERE 1 or username = \'
And I don't think we have to worry about those silly usernames getting access to our MySQL database. So please do use the handy mysql_real_escape_string() function to help prevent SQL Injection attacks on your websites. You have no excuse not to use it after reading this lesson!