Search This Blog

Showing posts with label CAKE PHP. Show all posts
Showing posts with label CAKE PHP. Show all posts

Monday, April 11, 2011

Generating and using Schema files :: Schema management and migrations :: Core Console Applications :: The Manual :: 1.2 Collection

Generating and using Schema files

A generated schema file allows you to easily transport a database agnostic schema. You can generate a schema file of your database using:
$ cake schema generate
This will generate a schema.php file in you app/config/sql directory.
The schema shell will only process tables for which there are models defined. To force the schema shell to process all the tables, you must add the -f option in the command line.

To later rebuild the database schema from your previously made schema.php file run:
$ cake schema run create
This will drop and create the tables based on the contents of the schema.php.
Schema files can also be used to generate sql dump files. To generate a sql file containing the CREATE TABLE statements, run:

$ cake schema dump filename.sql

Where filename.sql is the desired filename for the sql dump. If you omit filename.sql the sql dump will be output to the console but not written to a file.

Tuesday, February 15, 2011

Handling TimeZones in CakePHP

The web is a global resource for anything, anywhere, any timezone. But often times we are careless in consideration for people in other areas of the world. The different timezones offset people’s schedules from one area to the next. When handling user profiles (or anything for that matter) where date and time is involved we can do a little magic with our CakePHP app to make things a little more convenient for our users. How do we handle this you ask?
First lets say when a user logs in to their profile they can click to edit the profile, selects his/her timezone, and clicks save. Relative to GMT we can calculate offsets of each timezone, where GMT would = 0. So for instance Eastern Timezone for New York, US would be -5 since its 5 ours BEHIND GMT. So lets start by generating a dropdown list with cake with all the different timezones, then save this list to the users profile. If you are using Auth with CakePHP, you will likely have a users table, and we’ll add a decimal field called “timezone” to that table. Fortunately there is a helper to assist us with this dropdown in the bakery, Timezone Helper. By taking a look at the source you’ll notice all the labels associated with an offset “-5.0″ or “+3.0″. Also look a little closer and you might notice a few have actual decimal (Kabul is +4.5). So first things first, go ahead and install that Helper as those instructions say. Add it to your Edit view for users to edit their profile. Once included you just add the drop down to your form with:
 
echo $timezone->select('timezone'); 
Now each user should have a timezone attached to their profile. Now the trick to timezones is that no matter what the timezone of our server is, we just want to convert it to display to the user in that user’s preferred timezone. On the reverse side, if a user enters a datetime, we convert it back to the timezone of the server.
Lets start our with the user viewing a date from the server, in our view we want to convert it to the user’s preferred timezone set to their profile (which should now be stored in their session, I’ll demonstrate with Auth)
 
$time->format('F j, Y g:i:s a'$mydatenull$session->read('Auth.User.timezone')); 
Using the Time helper in CakePHP, the format function accepts a fourth parameter which indicates the timezone, which is extremely helpful. So this is all you need to do to display a time from the server to a user.
Next lets say the user is about to edit a field from the server in a form. First we need to select the existing data from the database, we’ll convert it to the user’s timezone, and place it in an input field to be edited. Then once the user saves the data we’ll simply convert it back to the server’s timezone. (There a bunch of “one liners” in doing all of these tasks). So if you have your Time helper in your controller when you get the data from the database, go ahead and convert it to the new timezone just like we did before:
 
$data['Model']['mydate'] = $time->format('Y-n-d H:i:sP'$data['Model']['mydate'], null$this->Auth->user('timezone')); 
Now in your view for the form there are a few different scenarios. 1) You use Cake’s default inputs for editing date times, with the 6 dropdowns, or 2) You use a plain input and use a date/time picker of some sort. Lets first handle the first scenario, Cakes default 6 input datetime. The data has been submitted, validated and we’re about to place it back in the database, we need to convert it back to server timezone. But wait! the form field is broken down into an array of six elements: year, month, day, hour, minute, meridian. Well we can create a nice little function that will convert this array into a datetime, and pass it our timezone:
 
function dateTimeArrayToServerTZString($dt$tz=0){ 
    $tz = (floatval($tz) >= 0)? '+'. number_format(floatval($tz),2,':','') : number_format(floatval($tz),2,':',''); 
    $dt['min'] = str_pad($dt['min'], 2"0"STR_PAD_LEFT); 
 
    $loc = $dt['year'] .'-'$dt['month'] .'-'$dt['day'] .' '$dt['hour'] .':'$dt['min'] .' '$dt['meridian'] .' '$tz; 
 
    $datetime = new DateTime($loc); 
    $datetime->setTimezone(new DateTimeZone(date('e', time()))); 
 
    return $datetime->format('Y-n-d H:i:sP'); 
} 
Now right before I insert my data into the database I just need to call this function on that datetime array:
 
$this->data['Model']['mydate'] = dateTimeArrayToServerTZString($this->data['Model']['mydate'], $this->Auth->user('timezone')); 
Now $this->data['Model']['mydate'] will be a string, and cake still knows how to handle that just fine. Now for the second scenerio, a user submitting a string. This isn’t too hard at all, we just use our time helper and convert that puppy back to the server time.
 
$this->data['Model']['mydate'] = $time->format('Y-n-d H:i:sP'$this->data['Model']['mydate'], null, -5); 
Ok, so I’ve hardcoded in the timezone to -5 (Eastern Timezone), what if I want this to be dynamic to where ever my server is? Well the Time helper has a function which isn’t mentioned in the book called serverOffset(), which will return a number of the offset. If you’re not using the helper and just want to get the timezone of the server its a simple one-liner:
 
date('Z', time()) 
Thats all there is to handling timezones in your cakePHP site, or any site for that matter. Just keep in mind as you go to convert any times for the user’s pleasure. You have any tips or alternatives?

Handling TimeZones in CakePHP

Thursday, December 2, 2010

PHP 6 Features

PHP is already popular, used in millions of domains (according to Netcraft), supported by most ISPs and used by household-name Web companies like Yahoo! The upcoming versions of PHP aim to add to this success by introducing new features that make PHP more usable in some cases and more secure in others. Are you ready for PHP V6? If you were upgrading tomorrow, would your scripts execute just fine or would you have work to do? This article focuses on the changes for PHP V6 — some of them back-ported to versions PHP V5.x — that could require some tweaks to your current scripts.
If you're not using PHP yet and have been thinking about it, take a look at its latest features. These features, from Unicode to core support for XML, make it even easier for you to write feature-filled PHP applications.
PHP V6 is currently available as a developer snapshot, so you can download and try out many of the features and changes listed in this article. For features that have been implemented in the current snapshot, see Resources.
Much improved for PHP V6 is support for Unicode strings in many of the core functions. This new feature has a big impact because it will allow PHP to support a broader set of characters for international support. So, if you're a developer or architect using a different language, such as the Java™ programming language, because it has better internationalization (i18n) support than PHP, it'll be time to take another look at PHP when the support improves.
Because you can download and use a developer's version of PHP V6 today, you will see some functions already supporting Unicode strings. For a list of functions that have been tested and verified to handle Unicode, seeResources.
What is Unicode?
Unicode is an industry-standard set of characters, character encoding, and encoding methodologies primarily aimed at enabling i18n and localization (i10n). The Unicode Transformation Format (UTF) specifies a way to encode characters for Unicode. For more information about Unicode and UTF, see Resources.
Namespaces are a way of avoiding name collisions between functions and classes without using prefixes in naming conventions that make the names of your methods and classes unreadable. So by using namespaces, you can have class names that someone else might use, but now you don't have to worry about running into any problems. Listing 1 provides an example of a namespace in PHP.
You won't have to update or change anything in your code because any PHP code you write that doesn't include namespaces will run just fine. Because the namespaces feature appears to be back-ported to V5.3 of PHP, when it becomes available, you can start to introduce namespaces into your own PHP applications.

Listing 1. Example of a namespace
<?php
// I'm not sure why I would implement my own XMLWriter, but at least
// the name of this one won't collide with the one built in to PHP
namespace NathanAGood;
class XMLWriter 
{
    // Implementation here...




}

$writer = new NathanAGood::XMLWriter();

?>

Depending on how you use PHP and what your scripts look like now, the language and syntax differences in PHP V6 may or may not affect you as much as the next features, which are those that directly allow you to introduce Web 2.0 features into your PHP application.
SOAP is one of the protocols that Web services "speak" and is supported in quite a few other languages, such as the Java programming language and Microsoft® .NET. Although there are other ways to consume and expose Web services, such as Representational State Transfer (REST), SOAP remains a common way of allowing different platforms to have interoperability. In addition to SOAP modules in the PHP Extension and Application Repository (PEAR) library, a SOAP extension to PHP was introduced in V5. This extension wasn't enabled by default, so you have to enable the extension or hope your ISP did. In addition, PEAR packages are available that allow you to build SOAP clients and servers, such as the SOAP package.
Unless you change the default, the SOAP extension will be enabled for you in V6. These extensions provide an easy way to implement SOAP clients and SOAP servers, allowing you to build PHP applications that consume and provide Web services.
If SOAP extensions are on by default, that means you won't have to configure them in PHP. If you develop PHP applications and publish them to an ISP, you may need to check with your ISP to verify that SOAP extensions will be enabled for you when they upgrade.
As of PHP V5.1, XMLReader and XMLWriter have been part of the core of PHP, which makes it easier for you to work with XML in your PHP applications. Like the SOAP extensions, this can be good news if you use SOAP or XML because PHP V6 will be a better fit for you than V4 out of the box.
The XMLWriter and XMLReader are stream-based object-oriented classes that allow you to read and write XML without having to worry about the XML details.

Back to top


In addition to having new features, PHP V6 will not have some other functions and features that have been in previous versions. Most of these things, such as register_globals and safe_mode, are widely considered "broken" in current PHP, as they may expose security risks. In an effort to clean up PHP, the functions and features listed in the next section will be removed, or deprecated, from PHP. Opponents of this removal will most likely cite issues with existing scripts breaking after ISPs or enterprises upgrade to PHP V6, but proponents of this cleanup effort will be happy that the PHP team is sewing up some holes and providing a cleaner, safer implementation.
Features that will be removed from the PHP version include:
  • magic_quotes
  • register_globals
  • register_long_arrays
  • safe_mode
Citing portability, performance, and inconvenience, the PHP documentation discourages the use of magic_quotes. It's so discouraged that it's being removed from PHP V6 altogether, so before upgrading to PHP V6, make sure that all your code avoids using magic_quotes. If you're using magic_quotes to escape strings for database calls, use your database implementation's parameterized queries, if they're supported. If not, use your database implementation's escape function, such as mysql_escape_string for MySQL or pg_escape_string for PostgreSQL. Listing 2 shows an example of magic_quotes use.

Listing 2. Using magic_quotes (discouraged)
<?php
// Assuming magic_quotes is on...
$sql = "INSERT INTO USERS (USERNAME) VALUES $_GET['username']";
?>

After preparing your PHP code for the new versions of PHP, your code should look like that in Listing 3.

Listing 3. Using parameterized queries (recommended)
<?php


// Using the proper parameterized query method for MySQL, as an example
$statement = $dbh->prepare("INSERT INTO USERS (USERNAME) VALUES ?");
$statement->execute(array($_GET['username']));




?>

Now that support for magic_quotes will be completely removed, the get_magic_quotes_gpc() function will no longer be available. This may affect some of the older PHP scripts, so before updating, make sure you fix any locations in which this functions exists.
The register_globals configuration key was already defaulted to off in PHP V4.2, which was controversial at the time. When register_globals is turned on, it was easy to use variables that could be injected with values from HTML forms. These variables don't really require initialization in your scripts, so it's easy to write scripts with gaping security holes. The register_globals documentation (see Resources) provides much more information aboutregister_globals. See Listing 4 for an example of using register_globals.

Listing 4. Using register_globals (discouraged)
<?php
// A security hole, because if register_globals is on, the value for user_authorized
// can be set by a user sending them on the query string 
// (i.e., http://www.example.com/myscript.php?user_authorized=true)




if ($user_authorized) {
    // Show them everyone's sensitive data...
}
?>

If your PHP code uses global variables, you should update it. If you don't update your code to get prepared for newer versions of PHP, consider updating it for security reasons. When you're finished, your code should look like Listing 5.

Listing 5. Being specific instead (recommended)
<?php
function is_authorized() {
    if (isset($_SESSION['user'])) {
        return true;
    } else {
        return false;
    }
}

$user_authorized = is_authorized();
?>




The register_long_arrays setting, when turned on, registers the $HTTP_*_VARS predefined variables. If you're using the longer variables, update now to use the shorter variables. This setting was introduced in PHP V5 — presumably for backward-compatibility — and the PHP folks recommend turning it off for performance reasons. Listing 6 shows an example of register_long-arrays use.

Listing 6. Using deprecated registered arrays (discouraged) 
<?php
    // Echo's the name of the user value given on the query string, like
    // http://www.example.com/myscript.php?username=ngood




    echo "Welcome, $HTTP_GET_VARS['username']!";
?>

If your PHP code looks like that shown in Listing 6, update it to look like that in Listing 7. Shut off theregister_long_arrays setting if it's on and test your scripts again.

Listing 7. Using $_GET (recommended)
<?php


    // Using the supported $_GET array instead.
    echo "Welcome, $_GET['username']!";
?>

The safe_mode configuration key, when turned on, ensures that the owner of a file being operated on matches the owner of the script that is executing. It was originally a way to attempt to handle security when operating in a shared server environment, like many ISPs would have. (For a link to a list of the functions affected by thissafe_mode change, see Resources.) Your PHP code will be unaffected by this change, but it's good to be aware of it in case you're setting up PHP in the future or counting on safe_mode in your scripts.
Microsoft Active Server Pages (ASP)-style tags — the shorter version of the PHP tags — are no longer supported. To make sure this is not an issue for your scripts, verify that you aren't using the <% or %> tags in your PHP files. Replace them with <?php and ?>.
The PHP team is removing support for both FreeType 1 and GD 1, citing the age and lack of ongoing developments of both libraries as the reason. Newer versions of both of these libraries are available that provide better functionality. For more information about FreeType and GD, see Resources.
The ereg extension, which supports Portable Operating System Interface (POSIX) regular expressions, is being removed from core PHP support. If you are using any of the POSIX regex functions, this change will affect you unless you include the ereg functionality. If you're using POSIX regex today, consider taking the time to update your regex functions to use the Perl-Compatible Regular Expression (PCRE) functions because they give you more features and perform better. Table 1 provides a list of the POSIX regex functions that will not be available after eregis removed. Their PCRE replacements are also shown.

Table 1. ereg() functions and their PCRE equivalents
ereg() functionSimilar preg() function
ereg()eregi()preg_match()
ereg_replace()ereg_replacei()preg_replace()

Wednesday, February 24, 2010

Install Cake PHP

tar -xvjf cake_1.3-dev.tar.bz2

mv cake_1.3-dev caketest

chmod -R 777 app/tmp

enable mod rewrite module on apache
in ubuntu sudo a2enmod rewrite
restart your web server

open app/config/core.php change the security salt new (md5 preferrable) value

save app/config/database.php.default as app/config/database.php change the following values for default variable
'driver' => 'mysql',//can be mysql,postgresql etc., we are going to use mysql
'persistent' => false,//will be use full if database server is on different machine
'host' => 'localhost', //not necessary  if you have your db on the same machine
'login' => 'sundar',
'password' => '*******************',
'database' => 'caketest',
'prefix' => '', // not necessary

give a link on your web server to point this folder

if every thing goes fine you will be seeing a webpage like this

Wednesday, February 3, 2010

KcacheGrind Profiling for PHP -Speed up Your Scripts

To check the time taken to execute a query we can use \timing on the psql prompt with Analyze and Verbose
To check the render engine we can use fire bug and firephp with YSlow,Jiffy etc., (even we can debug javascript and go for line by line execution of all the client side script )

For PHP code

While we write a code or test a code we are not able to clearly check how much time it will take for executing part of code (loops,functions) , How many times each function are called etc., to track this we have many tools like APD,XDebug

Herewith I am giving the steps to install and check the efficiency of code using XDebug



Installation and configuring(XDebug)

1) sudo pecl install xdebug

2) zend_extension =/usr/lib64/php5/extensions/xdebug.so
or
zend_extension =/usr/lib/php5/extensions/xdebug.so
xdebug.profiler_enable=1
xdebug.profiler_output_dir=[/home/myhome/apdtrace/]

3) sudo httpd restart

Now try to view the output of your phpinfo() function. If you find xdebug word in that then it means you have successfully installed xdebug.

Install kcachegrind
option 1
use YAST->software Management->Search->kcachegrind
accept the proposal
option 2
sudo apt-get -y install kcachegrind (for debian Systems)

Add these Lines on your code(recommended) or php.ini
ini_set('xdebug.collect_vars', 'on');
ini_set('xdebug.collect_params', '4');
ini_set('xdebug.dump_globals', 'on');
ini_set('xdebug.dump.SERVER', 'REQUEST_URI');
ini_set('xdebug.show_local_vars', 'on');

execute your code on browser you will get a file named cachegrind.out. on your output directory
open the file with your kcachegrind now you can clearly dissect your code and remove unnecessary code and loops and check the speed again