KOHANA- yet another PHP Framework

kohona-banner

kohona-banner

Every one may be know many frameworks for PHP, some may even don’t know about PHP frameworks, basically frameworks are a solution which is mainly reducing the development time and making the product in a world known standard.

So this is an introduction for another framework call kohana, name is bit like African or Indonesian, why not sometime this name is like an Hindi word, I am not going to research the name :). So will know some attractive features of kohana;

What is KOHANA

It’s a PHP 5 framework complete Object oriented and Model view controller enabled. If briefing more, a Swift, Small and Tiny, Secured and complete PHP 5framework.

As features (as per official document)

  • Highly secure
  • Extremely lightweight
  • Short learning curve
  • Uses the MVC pattern
  • 100% UTF-8 compatible
  • Loosely coupled architecture
  • Extremely easy to extend ( as same as codeigniter)

Technology

  • Strict PHP 5 OOP
  • Simple database abstraction using SQL helpers
  • Multiple session drivers (native, database, and cookie)
  • Powerful event handler allows small modifications dynamically
  • Originally based on CodeIgniter

Why KOHANA

You may ask why kohana is so special, few reasons, and those are very highly strong and those are highly appreciated by all most everyone.

  • Fully community driven (un like codeigniter)
  • One hundred person PHP 5 and Fully Object Oriented
  • No dependency with other packages
  • Much better Event handler
  • Very suitable for Rapid development cycle

How to start

Starting is really simple, basically you should know some PHP and some OOP concepts, (of course you should know HTML, CSS, JavaScript for better solution) than that you should have a localhost, and kohana framework, you can get them form following;

Also if you having any question or further reading try out for the official forum and the official help guide else read some tutorials and learn.

Conclusion

I guess these are main reasons that you should switch your framework (if your requirements suites above mentions), I am my view all most all the current projects that I am working is very rapid, so I am switched to kohana, if you see these point are valid you also simply use it.

Author: Yoosufs

Advertisements

Making stylish button with CSS Sliding Door

sliding door button with css

sliding door button with css

Recently I saw the Sliding Door like buttons in WordPress.com site, I am so liked that and thought of making a sample one and I was all most success. So I thought of sharing that with you. It’s not a hard part, but I spend around thirty minutes to do this, I was so sad because I spent much time to do this, but finally I was really happy I learned some CSS in that thirty minutes. But any way will dive in and just have a look on how to make.

Download: http://www.box.net/shared/8u1h5xsk0t

Download PSD: http://www.box.net/shared/a5rvfz3yzs

That’s it, if you want to try out by yourself, get the files, try your seft and optimize as you wish, use it In your site, if possible else if you have a optimized why shout out in the comments. So far this solution is checked with following browsers;

  • Safari 4
  • Mozilla 3.5
  • Internet Explorer 8

Just checked with Opera 9.64 and Internet Explore 7, it’s working fine 🙂

For lower browser check I don’t have much resource, if possible try it yourself :).

Author: Yoosufs

Cut html string without cutting html tags

<?php

class HtmlCutString{
function
__construct($string, $limit){
// create dom element using the html string
$this->tempDiv = new DomDocument;
$this->tempDiv->loadXML('<div>'.$string.'</div>');
// keep the characters count till now
$this->charCount = 0;
$this->encoding = 'UTF-8';
// character limit need to check
$this->limit = $limit;
}
function
cut(){
// create empty document to store new html
$this->newDiv = new DomDocument;
// cut the string by parsing through each element
$this->searchEnd($this->tempDiv->documentElement,$this->newDiv);
$newhtml = $this->newDiv->saveHTML();
return
$newhtml;
}

function deleteChildren($node) {
while (isset(
$node->firstChild)) {
$this->deleteChildren($node->firstChild);
$node->removeChild($node->firstChild);
}
}
function
searchEnd($parseDiv, $newParent){
foreach(
$parseDiv->childNodes as $ele){
// not text node
if($ele->nodeType != 3){
$newEle = $this->newDiv->importNode($ele,true);
if(
count($ele->childNodes) === 0){
$newParent->appendChild($newEle);
continue;
}
$this->deleteChildren($newEle);
$newParent->appendChild($newEle);
$res = $this->searchEnd($ele,$newEle);
if(
$res)
return
$res;
else{
continue;
}
}

// the limit of the char count reached
if(mb_strlen($ele->nodeValue,$this->encoding) + $this->charCount >= $this->limit){
$newEle = $this->newDiv->importNode($ele);
$newEle->nodeValue = substr($newEle->nodeValue,0, $this->limit $this->charCount);
$newParent->appendChild($newEle);
return
true;
}
$newEle = $this->newDiv->importNode($ele);
$newParent->appendChild($newEle);
$this->charCount += mb_strlen($newEle->nodeValue,$this->encoding);
}
return
false;
}
}

Example:

function cut_html_string($string, $limit){
$output = new HtmlCutString($string, $limit);
return
$output->cut();
}

?>

Author:  prajwala

Optimizing JavaScript code

Authors: Gregory Baker, Software Engineer on GMail & Erik Arvidsson, Software Engineer on Google Chrome

Recommended experience: Working knowledge of JavaScript

Client-side scripting can make your application dynamic and active, but the
browser’s interpretation of this code can itself introduce
inefficiencies, and the performance of different constructs varies from
client to client. Here we discuss a few tips and best practices to
optimize your JavaScript code.

Working with strings

String concatenation causes major problems with Internet Explorer 6 and 7
garbage collection performance. Although these issues have been
addressed in Internet Explorer 8 — concatenating is actually slightly more

efficient on IE8 and other non-IE browsers such as Chrome — if a
significant portion of your user population uses Internet Explorer 6 or
7, you should pay serious attention to the way you build your strings.

Consider this example:

var veryLongMessage =

'This is a long string that due to our strict line length limit of' +

maxCharsPerLine +

' characters per line must be wrapped. ' +

percentWhoDislike +

'% of engineers dislike this rule. The line length limit is for ' +

‘ style purposes, but we don’t want it to have a performance impact.’ +

‘ So the question is how should we do the wrapping?’;

Instead of concatenation, try using a join:

var veryLongMessage =

['This is a long string that due to our strict line length limit of',

maxCharsPerLine,

' characters per line must be wrapped. ',

percentWhoDislike,

‘% of engineers dislike this rule. The line length limit is for ‘,

‘ style purposes, but we don’t want it to have a performance impact.’,

‘ So the question is how should we do the wrapping?’

].join();

Similarly, building up a string across conditional statements and/or loops by
using concatenation can be very inefficient. The wrong way:

var fibonacciStr = 'First 20 Fibonacci Numbers

‘;

for (var i = 0; i < 20; i++) {

fibonacciStr += i + ‘ = ‘ + fibonacci(i) + ‘

‘;

}

The right way:

var strBuilder = ['First 20 fibonacci numbers:'];

for (var i = 0; i < 20; i++) {

strBuilder.push(i, ‘ = ‘, fibonacci(i));

}

var fibonacciStr = strBuilder.join(”);

Building strings with portions coming from helper functions

Build up long strings by passing string builders (either an array or a helper
class) into functions, to avoid temporary result strings.

For example, assuming buildMenuItemHtml_ needs to build up a string from literals and variables and would use a string builder internally, instead of using:

var strBuilder = [];

for (var i = 0; i < menuItems.length; i++) {

strBuilder.push(this.buildMenuItemHtml_(menuItems[i]));

}

var menuHtml = strBuilder.join();

Use:

var strBuilder = [];

for (var i = 0; i < menuItems.length; i++) {

this.buildMenuItem_(menuItems[i], strBuilder);

}

var menuHtml = strBuilder.join();

Defining class methods

The following is inefficient, as each time a instance of baz.Bar is constructed, a new function and closure is created for foo:

baz.Bar = function() {

// constructor body

this.foo = function() {

// method body

};

}

The preferred approach is:

baz.Bar = function() {

// constructor body

};

baz.Bar.prototype.foo = function() {

// method body

};

With this approach, no matter how many instances of baz.Bar are constructed, only a single function is ever created for foo, and no closures are created.

Initializing instance variables

Place instance variable declaration/initialization on the prototype for
instance variables with value type (rather than reference type)
initialization values (i.e. values of type number, Boolean, null,
undefined, or string). This avoids unnecessarily running the
initialization code each time the constructor is called. (This can’t be
done for instance variables whose initial value is dependent on
arguments to the constructor, or some other state at time of
construction.)

For example, instead of:

foo.Bar = function() {

this.prop1_ = 4;

this.prop2_ = true;

this.prop3_ = [];

this.prop4_ = 'blah';

};

Use:

foo.Bar = function() {

this.prop3_ = [];

};

foo.Bar.prototype.prop1_ = 4;

foo.Bar.prototype.prop2_ = true;

foo.Bar.prototype.prop4_ = ‘blah’;

Avoiding pitfalls with closures

Closures are a powerful and useful feature of JavaScript; however, they have several drawbacks, including:

  • They are the most common source of memory leaks.
  • Creating
    a closure is significantly slower then creating an inner function
    without a closure, and much slower than reusing a static function. For
    example:

    function setupAlertTimeout() {

    var msg = 'Message to alert';

    window.setTimeout(function() { alert(msg); }, 100);

    }

    is slower than:

    function setupAlertTimeout() {

    window.setTimeout(function() {

    var msg = ‘Message to alert’;

    alert(msg);

    }, 100);

    }

    which is slower than:

    function alertMsg() {

    var msg = 'Message to alert';

    alert(msg);

    }

    function setupAlertTimeout() {

    window.setTimeout(alertMsg, 100);

    }

  • They add a level to the scope chain. When the browser resolves properties,
    each level of the scope chain must be checked. In the following example:

    var a = 'a';

    function createFunctionWithClosure() {

    var b = ‘b’;

    return function () {

    var c = ‘c’;

    a;

    b;

    c;

    };

    }

    var f = createFunctionWithClosure();

    f();

    when f is invoked, referencing a is slower than referencing b, which is slower than referencing c.

See IE+JScript Performance Recommendations Part 3: JavaScript Code inefficiencies for information on when to use closures with IE.

Avoiding with

Avoid using with in your code. It has a negative impact on performance, as it modifies
the scope chain, making it more expensive to look up variables in other
scopes.

Avoiding browser memory leaks

Memory leaks are an all too common problem with web applications, and can
result in huge performance hits. As the memory usage of the browser
grows, your web application, along with the rest of the user’s system,
slows down. The most common memory leaks for web applications involve
circular references between the JavaScript script engine and the
browsers’ C++ objects’ implementing the DOM (e.g. between the
JavaScript script engine and Internet Explorer’s COM infrastructure, or
between the JavaScript engine and Firefox XPCOM infrastructure).

Here are some rules of thumb for avoiding memory leaks:

Use an event system for attaching event handlers

The most common circular reference pattern [ DOM element –> event
handler –> closure scope –> DOM ] element is discussed in this MSDN blog post. To avoid this problem, use one of the well-tested event systems for attaching event handlers, such as those in Google doctype, Dojo, or JQuery.

In addition, using inline event handlers can lead to another kind of leak
in IE. This is not the common circular reference type leak, but rather
a leak of an internal temporary anonymous script object. For details,
see the section on “DOM Insertion Order Leak Model” in Understanding and Solving Internet Explorer Leak Patterns and and an example in this JavaScript Kit tutorial.

Avoid expando properties

Expando properties are arbitrary JavaScript properties on DOM elements and are
a common source of circular references. You can use expando properties
without introducing memory leaks, but it is pretty easy to introduce
one by accident. The leak pattern here is [ DOM element –> via
expando–> intermediary object –> DOM element ]. The best thing
to do is to just avoid using them. If you do use them, only use values
with primitive types. If you do use non-primitive values, nullify the
expando property when it is no longer needed. See the section on
“Circular References” in Understanding and Solving Internet Explorer Leak Patterns.

PHP performance tips

PHP is a very popular scripting language, used on many popular sites across
the web. In this article, we hope to help you to improve the
performance of your PHP scripts with some changes that you can make
very quickly and painlessly. Please keep in mind that your own
performance gains may vary greatly, depending on which version of PHP
you are running, your web server environment, and the complexity of
your code.

Profile your code to pinpoint bottlenecks

Hoare’s dictum states that Premature optimization is the root of all evil,
an important thing to keep in mind when trying to make your web sites
faster. Before changing your code, you’ll need to determine what is
causing it to be slow. You may go through this guide, and many others
on optimizing PHP, when the issue might instead be database-related or
network-related. By profiling your PHP code, you can try to pinpoint bottlenecks.

Upgrade your version of PHP

The team of developers who maintain the PHP engine have made a number of
significant performance improvements over the years. If your web server
is still running an older version, such as PHP 3 or PHP 4, you may want
to investigate upgrading before you try to optimize your code.

Use caching

Making use of a caching module, such as Memcache, or a templating system which supports caching, such as Smarty, can help to improve the performance of your website by caching database results and rendered pages.

Use output buffering

PHP uses a memory buffer to store all of the data that your script tries to
print. This buffer can make your pages seem slow, because your users
have to wait for the buffer to fill up before it sends them any data.
Fortunately, you can make some changes that will force PHP to flush the
output buffers sooner, and more often, making your site feel faster to
your users.

Don’t copy variables for no reason

Sometimes PHP novices attempt to make their code “cleaner” by copying predefined
variables to variables with shorter names before working with them.
What this actually results in is doubled memory consumption, and
therefore, slow scripts. In the following example, imagine if a
malicious user had inserted 512KB worth of characters into a textarea
field. This would result in 1MB of memory being used!

$description = strip_tags($_POST['description']);

echo $description;

There’s no reason to copy the variable above. You can simply do this operation inline and avoid the extra memory consumption:

echo strip_tags($_POST['description']);

Avoid doing SQL queries within a loop

A common mistake is placing a SQL query inside of a loop. This results in
multiple round trips to the database, and significantly slower scripts.
In the example below, you can change the loop to build a single SQL
query and insert all of your users at once.

foreach ($userList as $user) {

$query = ‘INSERT INTO users (first_name,last_name)
VALUES(“‘ . $user[‘first_name’] . ‘”, “‘ . $user[‘last_name’] . ‘”)’;

mysql_query($query);

}

Produces:

INSERT INTO users (first_name,last_name) VALUES("John", "Doe")

Instead of using a loop, you can combine the data into a single database query.


$userData = [];

foreach ($userList as $user) {

$userData[] = ‘(“‘ . $user[‘first_name’] . ‘”, “‘ . $user[‘last_name’] . ‘”)’;

}

$query = ‘INSERT INTO users (first_name,last_name) VALUES’ . implode(‘,’, $iserData);

mysql_query($query);Produces:

INSERT INTO users (first_name,last_name) VALUES("John", "Doe"),("Jane", "Doe")...

Use single-quotes for long strings

The PHP engine allows both single-quotes and double-quotes for string
variable encapsulation, but there are differences! Using double-quotes
for strings tells the PHP engine to read the string contents and look
for variables, and to replace them with their values. On long strings
which contain no variables, that can result in poor performance.

$output = "This is the content for a very long article

which is a few hundred lines long

and goes on and on and on

The End";

Changing the double-quotes to
single-quotes prevents the PHP engine from parsing this string in an
attempt to expand variables which, in this example, don’t exist:

$output = 'This is the content for a very long article

which is a few hundred lines long

and goes on and on and on

The End';

Use switch/case instead of if/else

Using switch/case statements rather than loose-typed if/else statements when
testing against a single variable results in better performance,
readability, and maintainability. It’s important to note that using
switch/case does a loose-comparison, and should be taken into consideration when being used.

if($_POST['action'] == 'add') {

addUser();

} elseif ($_POST[‘action’] == ‘delete’) {

deleteUser();

} elseif ($_POST[‘action’] == ‘edit’) {

editUser();

} else {

defaultAction();

}

Instead, you can use switch/case to test against the value of $_POST['action']:

switch($_POST['action']) {

case ‘add’:

addUser();

break;

case ‘delete’:

deleteUser();

break;

case ‘edit’:

editUser();

break;

default:

defaultAction();

break;

}

Additional resources

Author: Eric Higgins, Google Webmaster

Recommended experience: Beginner to intermediate PHP knowledge

« Older entries