Django vs Rails

Posted by admin on Friday Jun 20, 2008 Under Django, Ruby on Rails

Reddit had a link today to a blog entry called Why Django kicks Ruby on Rail’s collective ass in which the author mentions his reasons for prefering Django. As someone who’s using Django at work this week (and hopefully in the next), I would like to comment on his points.

Python

The author prefers Python over Ruby. I like them both, I couldn’t say which I prefer, although I would lean towards Python these days. Then there’s some stupid talk about how if Adrian a Jacob died that the continued development of Django would easier than if DHH died. His rationale is that there are more Python programmers, but it doesn’t take 10,000 code monkeys, just a few qualified developers and both groups have that, so that point is pretty moot.

Documentation

I don’t agree that Django’s documentation kicks RoR’s ass. The “prose” documentation on their official website is good, however I would really, really like documentation like Ruby’s API documentation. The author calls it “massively confusing”; it might be for beginning programmers or non-programmers (like designers), but as a developer I would really like that kind of documentation for Django. I can get a somewhat equivalent by using the python interpreter’s dir() and help() functions, however the navigation between different elements is hard. Sometimes I really want to know all the methods and attributes available for a class or what keyword parameters I can give to a method, and Django’s current documentation doesn’t cover that.

Templating

I like Django’s templating, because since it’s limited, you can’t begin mixing code that should be in the template and code that should be in the view. This helps keep things where they belong. As mentionned, the templates are also friendlier to non-programmer.

Speed

Python is faster than Ruby. Not much else to say here. Django has also proven faster than Rails.

Free, JustWorks Admin interface

I must admit that this is probably the best feature of Django. Sometimes, I wonder why I am bothering to create my own CRUD views when this is available (I am writing my own because I want to learn about more than just the admin interface if you must know.) I really like the idea of quickly whipping out a model, giving access to the admin interface to a content producer so that he can immediatly begin inputting data, before the views are complete.

Generic views and feeds

Those are fun too. In the app I’m writing, I use object_list and object_detail. They’re pretty fun to use. I have yet to create an RSS feed, but that’ll come.

Better support and server

As far as I know, Django doesn’t yet support MS SQL as the author claims. Support for MS SQL and Oracle is upcoming however, but in the mean time, I think that Rails has more database support. Whether it’s a hack or not, I don’t know. For web servers, I pretty much agree that mod_python > FastCGI.

Django is (mostly) buzzword free

It’s true that you don’t hear nearly as much hype about Django as with Rails, and as DHH once said about Rails (before it hit REALLY big), it’s a good thing to have a smaller community, because you don’t necessarily end up with mediocre developpers polluting the community. This happened to Perl with CGI.pm and to PHP.

Tags : | 4 comments

Django on Windows

Posted by admin on Thursday Jun 5, 2008 Under Django, Python

Back in April 2006, I wrote a HOWTO for installing Django on Windows (link). Since that time, that guide has become quite popular and linked from various places. Unfortunately some of the information in it has become outdated and so it was time to update it.

This page is the new/revised guide that I will be keeping up to date with the latest information. If you have any comments or tips, please post them below.

Enjoy.

Step 0. Read the official documentation

There was a time when the Django documentation, while quite good, was missing quite a bit. But these days it really has just about everything you need. Your first stop should be at the official site to check out the following:

All done? Let’s move on.

Step 1. Install Python

Current version: Python 2.5 (win32)

The first step is to get the latest version of Python installed. Head on over to Python.org and download the latest Windows installer. Double click and run.

For the rest of this guide, the assumption is that you installed Python in C:\Python25\.

Step 2. Install PostreSQL and Psycopg

Current version: PostreSQL 8.2.3 (win32), Psycopg2 2.0.5.1 (win32)

Django supports a few different databases including PostgeSQL, MySQL, and SQLite. Personally, I’m a fan of SQLite for small projects that won’t be getting a huge amount of traffic. PostgreSQL is, however, the “recommended” database for use with Django, so we’ll use that one.

Go the PostgreSQL Downloads page (or FTP Browser) and get the latest Windows version that includes the installer.

Unpack the zip and you’ll have three files (including a README.TXT). Double click the msi file and then walk through the installer. The default options for what gets installed will probably be fine, but take a look through the options and see if there is anything else you want (e.g. PL/Java). Make sure that you have psql and pgAdmin III selected to be installed. You’ll need those:

You will be asked if you want to run Postgres as a service. If you are running Windows 2000 or Windows XP (so it’s an option) I highly recommend you say yes. It will automatically start the database and run it in the background so it’s there when you need it. You’ll need to pick a username and password for the Windows account for the service. It will create the user account for you if it doesn’t already exist.

When configuring your cluster, the default port of 5432/tcp should be fine unless you have a compelling reason to use something else. Select the proper locale (English, United States for me), and encoding (cool kids use UTF-8). You’ll also need to pick your Postgres superuser name and password. Note that this is not the same as the Windows account the service will be running as, and in fact it is not recommended to have the same password for both. I do recommend using postgres as the username, and a nice secure password:

Click through the final screens and finish. You should now have PostgreSQL installed and running as a service. To try it out, go to Start | Programs | PostgreSQL | pgAdmin III and run it. If you have Postgres running properly you should be able to double click on “PostgreSQL Database Server” and see something like the following:

To get Python to talk to the database, you’ll need Psycopg. According to the official Django docs, “version 2 is recommended with postgresql_psycopg2 backend, version 1.1 works also with the postgresql backend.”

The installation is simple, just download the installer built for Windows (i.e. win-psycopg) and run it. But make sure that you grab the right version! Your Psycopg version must be built to match both your Python version and your PostgreSQL version.

Step 3. Install Subversion (SVN)

Current version: Subversion 1.4.3 (win32)

Although you can always install the latest official release of Django, I’ve found that with the amount of active development going on, it’s probably a good idea to grab the latest version from SVN. That’s a lot easier than it sounds, but you will have to install Subversion for Windows to make it happen.

Go to the Subversion Downloads page and download the latest Windows installer with the basic win32 binaries. Once again, the actual installation is simple and consists of clicking through the installer steps.

Also, if you want something a little easier than the command line, you should check out TortoiseSVN. It integrates quite nicely with Windows, and I’ve been quite happy with it so far. You do not, however, need to install it.

Step 4. Install and test Django

Current version: 0.96-pre (svn)

Open a command prompt and change the directory and check out the latest revision from SVN:

C:\> cd C:\Python25\Lib\site-packages C:\Python25\Lib\site-packages> svn co http://code.djangoproject.com/svn/django/trunk/django django

It will create a django directory and install a lot of files. Eventually it will finish with something similar to the following:

... A C:\Python25\lib\site-packages\django\middleware\http.py A C:\Python25\lib\site-packages\django\middleware\locale.py A C:\Python25\lib\site-packages\django\middleware\cache.py A C:\Python25\lib\site-packages\django\middleware\doc.py U C:\Python25\lib\site-packages\django Checked out revision 4714. C:\Python25\Lib\site-packages>

Make a copy of django-admin.py (located in django\bin) and put it in C:\Python25\Scripts. That will make it easier to run in the future. Also, see the note at the end of this guide for tips on setting your Path environment variable.

Congrats, Django is now installed on your system!

By the way, if you ever want to update your Django source to the latest revision, just cd into your django directory and run svn update from there:

C:\Python25\Lib\site-packages>cd django C:\Python25\Lib\site-packages\django>svn update U core\management.py Updated to revision 4716.

At this point, it would probably be a good idea to make sure that your Django install works before you attempt to get it working with Apache and mod_python. So let’s use the tutorial to create a basic Django project and test the setup:

C:\Documents and Settings\John>cd C:\ C:\>cd django C:\django>django-admin.py startproject testproject C:\django>cd testproject C:\django\testproject>python manage.py runserver Validating models... 0 errors found. Django version 0.96-pre, using settings 'testproject.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [12/Mar/2007 20:45:50] “GET / HTTP/1.1″ 404 2063

Assuming you didn’t get any errors, you should be able to open your browser and confirm that it works:

Step 5. Install Apache and mod_python

Current version: Apache 2.2.4, mod_python 3.3.1

Next up is Apache

While Django does come with an extremely handy development server that you can use for coding and testing apps, you’ll eventually want to be able to push your application into production. So it’s probably a good idea to get a real Apache install up and running that you can play with.

Installing Apache 2.x on Windows wasn’t nearly as difficult as I thought it would be. Basically head on over to the Apache site and grab the latest win32 binaries.

Double click and run the installer. If you get errors saying that the Installation Wizard was interrupted, check out my post about that.

You will need to enter some information about your system. Your network name will generally be your domain (e.g. thinkhole.org). Your server name will probably either be localhost if you only want local access, or your full hostname if you want to be able to access it over the net (e.g. serpent.thinkhole.org). Enter an email address for the administrator and select the option to install for all users on port 80.

Note that if you choose to run Apache on port 8000, it will conflict with the default port for the Django development/test server. Not cool.

Now test to see if Apache is up and running. Point your favorite browser at http://localhost (or 127.0.0.1) and see what happens. If you a see a page similar to the following, you are all set:

A nice feature of Apache on Windows (did I just say that?!) is the Apache Service Monitor that you can access via the icon in the bottom-right of your screen. Just click on it and it will come up. From there you can stop, start, and restart the server:

Quite handy.

Now that Apache is working, it’s time to install mod_python. Download the win32 binaries that match both your Python version and your Apache version. Double click the installer and follow the instructions in the Wizard:

Note that when it asks you for where Apache is installed, in most cases that will be here:

C:\Program Files\Apache Software Foundation\Apache2.2\

After the installer finishes, you still have one more thing to do. Open your Apache configuration file, usually located at C:\Program Files\Apache Software Foundation\Apache2.2\conf\httpd.conf with notepad. Scroll down and look for a section that includes a bunch of lines that start with LoadModule. Add the following line to that section:

LoadModule python_module modules/mod_python.so

Save the file and close it. Open up the Apache Service Monitor and click Restart. You should see the following text:

The Apache2 service is restarting. The Apache2 service has restarted.

If you get errors, you probably made a typo in the configuration file when you were editing it. Check it and try again. If you don’t have any errors, you should be all set.

Step 6. Configure Apache for Django

Now that everything is installed and we know that Django is working properly, it’s time to get it working with Apache and mod_python.

Open your Apache2 config file located at C:\Program Files\Apache Software Foundation\Apache2.2\conf\httpd.conf and add the following to the bottom of the file:

<Location "/testproject/"> SetHandler python-program PythonPath "['C:/django'] + sys.path” PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE testproject.settings PythonDebug On </Location> <Location “/media/”> SetHandler None </Location> <LocationMatch “\.(jpg|gif|png)$”> SetHandler None </LocationMatch>

Make sure you restart Apache after making the changes to httpd.conf.

Assuming there were no errors in any of the steps up to this point, you should now be able to browse to localhost/testproject and be greeted with this page:

If that’s what you see, then you have Django installed and running via Apache and mod_python, ready for anything you can throw at it. Congrats!

Troubleshooting/Notes:

  • You might need to adjust your PATH environment variable to make all of this work. To do so, right click My Computer and hit Properties. Go the Advanced tab and click on Environment Variables. Select the Path system variable from the list and click Edit. Make sure that all of the following are included in your path (i.e. Variable value), separated by semicolons:C:\Python25\Scripts; C:\Python25; C:\Program Files\Subversion\bin;Some people seem to use C:\Python25\tools instead of “scripts”… seems odd to me, but if that’s the case, you’ll need to adjust your path accordingly. That should fix most “command not found” type errors.

    Note that if you alter your path while you have a cmd.exe console open, you must restart the console before the changes will take effect.

  • According to Phil, having Cygwin installed can potentially screw up your paths. If you are getting ImportErrors, check Colin and Phil’s comments comment below.
  • See the comments by Edward Edmonds, Morg, and Nils-Hero below regarding escaping PythonPath in httpd.conf.
Tags : | add comments

My Suggestions for Google Top ranking

Posted by admin on Tuesday Mar 4, 2008 Under Open source, PHP

My Suggestions for Google Top ranking

 

Create City wise Sub domains

like pune.yourdomain.com, Mumbai.yourdomain.com

 

in pune.yourdomain.com upload whole website or redirect to our yourdomain.com site

Another way upload whole website but disable only selected means pune city in search criteria.

 

Google collect all website data every week on Sunday. He catches many types of data like meta description, meta keywords, page information, page name, page content. But Google give First preference to website name than WebPages name (page title).

 

That’s why suggested to create simple city wise and favorite category wise sub domains. This is very powerful system which we have implement and improve.

 

Google can catch our sub domains and there different types of data means specialize (city wise and favorite category wise) information of rental activity in that city or that category.

 

This is technically possible anytime. Not so much hard work. No database mismatch or No additional database required. no additional mail required ( but if we create mail like pune@yourdomain.com, Mumbai@yourdomain.com ) this is very better for Google top ranking. Pune rental requirement come on only pune@yourdomain.com

 

Now we hosted our website in Godaddy.com. We can create 10 sub domain in our hosting plan.

 

This is very simple and achieving idea for Google top ranking.

 

Pl read my Search engine Report because we use Php and Mysql Technology in our Web portal. What Google did for data collection and what criteria they use for ranking or listing of website? I read many articles and used many soft wares and programs for Google ranking.

 

I am pretty glad to tell you. I suggested techniques are very helpful for our achievement.

 

This techniques used by many website like

 

(pune.magicbricks.com, pune.indiaproperty.com, realestate.virtualpune.com, apartment. magicbricks.com, pune.click.in, Bharatmatrimonial.com and many more)

 

Search Engine Optimizing PHP Report

 

PHP pages have a reputation of being more difficult (or at least different) to SEO than static HTML pages. Here?s an overview of the major issues encountered when trying to optimize PHP script for search engines. While this focuses on PHP much of it is still relevant to SEO’ing dynamic pages in general.

PHP Speed

While page size does affect load time, spiders run on servers connected to high bandwidth networks, so download time is less important than the latency of the PHP script?s execution time. If a search engine spider follows a link on a site and is forced to wait too long for the server to process the PHP code behind that page, it may label your page as unresponsive.

The biggest delays in a PHP script typically are the database and loop code. Avoid making SELECT * calls, instead explicitly name all the columns you want to retrieve, and if you are using MySQL, test your queries using the EXPLAIN statement. To optimize loops consider using duplicated code instead of loops that don’t repeat very many times, also use as many static values, such as count($array) values inside the loop as you can, generating their values before the loop once.

URL Cleanliness

A major goal in SEO’ing your PHP pages, is to make them look and act like static pages. If you have a large site you can use Apache to fake static looking URLs, or, with a smaller site, you can simply keep your GET variables to a useful minimum. In either case, however, never allow a spider to see links with different URL?s to the same content. If the URL is different, the page should be too.

One of the major problems most webmasters have with getting their dynamic pages to index is URL cleanliness. Since many dynamic pages are created with GET variables, lots of pages have URLs that look like:

Page.php?var=lkdjdfhv&var2=345&var3=kfjdks

Most of the search engines will be able to follow this link, because it has 3 or under get variables (a good rule of thumb is to keep the number of GET variables passed in the URL to under 3), but any more than 3 variables and you will run into problems. Try using less GET variables, and make them more relevant, rather that useless id numbers use titles, and other keyword rich bits of text. This is an example of a better URL:

Page.php?var=category&var2=topic

If the page requires more variables you may want to consider combining the variables by delimiting them with a hyphen or another unused character, and then splitting the variable in the target page.

Disabling Trans_sid

Possibly the biggest cause of webmaster frustration when SEO?ing php pages is PHP?s tendency to add session id numbers to links if cookies are rejected by the browser (Search engine spiders reject cookies). This will happen by default if your PHP installation was compiled with the ?enable-trans-sid option (and this is the default from version 4.2 onward), and it creates links with an additional, long nonsense looking GET variable. In addition to making the links clunky this gives spiders different URLs with the same content, which makes them less likely to treat the pages individually, and possibly not even index them at all. A quick way to fix this is to disable the trans-id feature, if you have access, in php.ini by setting ?session.use_trans_sid? to false. If you don?t have access to change php.ini you can add this line to the .htaccess file in your root directory:

<IfModule mod_php4.c> php_flag session.use_trans_sid off </IfModule>

Masking dymamic URLs

However the mere presence of a question mark in the URL will introduce a delay in google?s indexing of the page. This from Mike Grehan?s Interview with Daniel Dulitz of Google:

?So the mere presence of a question mark in the URL doesn’t throw us for a loop at all. We will crawl those pages more slowly than we do with pages without question marks in the URL. Purely because they’ve identified themselves as being dynamic and we certainly don’t want to bring anyone’s site down because we’re hitting the database too hard.?

Small sites will not need to worry much about this delay as it means your server is hit every few minutes, not a few times a second, but for larger sites this can slow down your site?s inclusion into the index.

Making dynamic pages look static without mod_rewrite

A way to mask bulky dynamic page URLs (and avoid the question mark delay) is Apache?s ForceType in combination with a PHP command to interpret URLs like: www.example.com/books/computers.html as referring to a page called ?books? which is executed as a PHP script (I usually make a link on the linux server from ?books.php? to ?book? to make editing the script easier). The function will return an array of the additional values, including the category ?computers?. This can be accomplished by inserting a line like this into the .htaccess file in the root of your web documents directory:

<Files *Directory Handle Name Here*> ForceType application/x-httpd-php </Files>

*Directory Handle Name Here* should be replaced with the alias name you are giving to the fake directory you are creating. In this example:

www.example.com/books/computers.html

your .htaccess line would look like this:

<Files books>ForceType application/x-httpd-php</Files>

You can then log into your server and create a link to the file ?books? or whatever directory alias you have choosen. This is done with the linux command “ln”, or link, like this:

$ Ln books.php books

This creates a link between the existing PHP script books.php and the non-existant ?books?. This way all requests for the directory “books” will be given to books.php, ie www.example.com/books/computers.html would be handled by books.php

Inside books.php you can use this function (available here) to extract values from the static-looking request URI?s:


<?php
function processURI() {
    $request = explode(“/”,$_SERVER["REQUEST_URI"]);
    $count = count($request);     
    for ($i = 1 ; $i < $count ; $i++) {              
        $values["arg".$i] = $request[$i];   
    }
    return $values;   
}
?>
1

So the above example of: www.example.com/books/computer.html would be processed like this:


<?php
$vals = processURI();
$_GET[$vals[1]] = str_replace(“.html”, “”, $vals[2]);
?>
1

With this, $_GET['books'] would equal “computer” similar to www.example.com/index.php?books=computer

PHP?s SEO Advantages

A great advantage to using dynamic pages as opposed to static pages is the ability to create content that is constantly changing and updated in real time. RSS headlines, randomly circulating content and other automatically ?fresh? content can boost your ranks in Google, and many other engines.

Another advantage to using PHP is that you can make simple modifications to many scripts to create relevant and fresh page titles. Since this is the most important on page factor in SEO special attention should be given to creating title tags that accurately reflect the page?s current content. Any html templates or used in PHP pages can be altered to contain this line:

<title><?=$page_title?></title>

With this, $page_title can be set to a keyword rich test describing the page. Title text is also important in improving the click-through from SERP?s, so be sure that the title tags doesn?t read like spam, but more like a human created title.

 

Tags : | add comments

PHP Breadcrumb - Create breadcrumb in php

Posted by admin on Wednesday Feb 27, 2008 Under PHP

What are breadcrumbs?

Well quite simply, in web page terms this refers to a list of links (usually at the top) that appear on a web page to tell the user where they are in the structure of the website they are viewing. This makes navigating backward and forward so much easier as they have the ability to skip directly back through whole categories, rather than just using the browser’s back button.

Example

The breadcrumbs.php include file:

Copy the code below, save it in a file called breadcrumbs.php and upload it to your site. This will print out a simple unordered list (<ul>) of the parent directories by directory name. The only edits you may wish to make to this file is to change the $ul_id='crumbs'; line if you wish to change the id of the <ul>. If you wish to add a background image or border etc to the <li> simply select it as #crumbs li{} and style.

<?
$ul_id='crumbs';
$bc=explode("/",$_SERVER["PHP_SELF"]);
echo '<ul id="'.$ul_id.'"><li><a href="/">Home</a></li>';
while(list($key,$val)=each($bc)){
 $dir='';
 if($key > 1){
  $n=1;
  while($n < $key){
   $dir.='/'.$bc[$n];
   $val=$bc[$n];
   $n++;
  }
  if($key < count($bc)-1) echo '<li><a href="'.$dir.'">'.$val.'</a></li>';
 }
}
echo '<li>'.$pagetitle.'</li>';
echo '</ul>';
?>

A script to insert in the HTML where you want the breadcrumbs to appear:

Edit the URI to point to where you saved the include file (once this is done it never needs to be changed again). Edit, ‘Insert Page Title’ to add the page title to the end of the breadcrumbs.

<?
$pagetitle="Insert Page Title";
include("http://www.yourdomain.com/breadcrumbs.php");
?>

Note: It would be useful to automatically print the page <title> as the last crumb but PHP cannot interogate the DOM. Javascript would be required which we didn’t think appropriate as nothing would be returned if Javascript was turned off.


Tags : | 1 comment

Retrieve page name in php

Posted by admin on Wednesday Feb 27, 2008 Under PHP

Many people facing this problem for many kind of situations like … create dynamic javascript or css menu..,  navigation,  hit counter… for page..

you can use set variable names for page.  second good way is use this function for print page name $_SERVER["PHP_SELF"]

or if you want only page name than use this script

<?php

$pagename=pathinfo($_SERVER["PHP_SELF"]);
$pagename=$pagename["basename"];

echo $pagename;

?>

Tags : | add comments

free software- open source technology

Posted by admin on Friday Feb 15, 2008 Under Open source

Advances in technology have revolutionized the way people live, learn and work, but these benefits have not spread around the world evenly. A digital divide exists between communities in their access to computers, the Internet, and other technologies. The United Nations is aware of the importance of including technology development as part of a larger effort to bridge this global digital divide. This article looks at how various United Nations agencies use free and open source software to meet the goal of putting technology at the service of people around the world.

The Millennium Development Goals

The Millenium Development Goals (MDGs) are a set of eight targets to help end extreme poverty worldwide by 2015. The United Nations Information and Communication Technologies Task Force, created in March 2001, has worked to advance the development goals and targets of the UN, in particular those set by the Millennium Declaration. The Global Alliance for ICT and Development (GAID) group replaced UNICTTF, and now has the task of providing an open policy dialogue on the role of information and communication technologies in development.

In their report The Role of Information and Communication Technologies in Global Development: Analyses and Policy Recommendations, the Task Force states that information and communication technologies will increasingly become one of the main enablers in the pursuit of poverty alleviation and wealth creation in developed and developing countries alike. It’s easy to overlook the importance of technology in development, though. When people are starving and don’t have access to clean water, does it matter if they have access to the Internet? Technology is not an end in itself in these situations, but it is a tool to achieve wider goals such as eradicating hunger and achieving universal primary education.

To help raise awareness of the potential for free and open source software in this area, various UN organizations and nonprofits have created the FOSS: Policy and Development Implications (FOSS-PDI) initiative. Part of this initiative consists of a mailing list that discusses specific FOSS applications that address the different MDGs, information about how different countries are using open source software, and coordination for events being planned around the world.

Tags : | add comments

PHP vs Ruby on Rails

Posted by admin on Friday Feb 15, 2008 Under PHP, Ruby on Rails

Over the last few weeks, I’ve been asked by both friends and clients, “So what is that thing called Rails I keep hearing about (and/or keep hearing you talk about)? How is it different from PHP?” Typically I give them a three-part answer that’ll I’ll now iterate for the blog. While this is far from a complete comparison, hopefully it will be useful to some people out there. The first thing to keep in mind when trying to form a comparison between PHP and Rails, is that PHP is just a language. It’s a scripting language that has a lot of useful functions that make adding dynamic content to web pages easier than its predecessors. What PHP is not (and what Rails, in fact, is) is a framework. In software terms, frameworks are generally tools and pre-built objects that help you create a solution faster by not reinventing the wheel.

More specifically, Rails is a full-stack framework. Full-stack basically means that when you decide to use Rails it will provide practically all of the tools necessary all by itself. While you are welcome to use other tools for sections of Rails’ functionality, most current Rails developers are not (and for obvious reasons described below).

So PHP is just a language. When you choose to use PHP to build a significant web application what you’ll want to do is look for tools and pre-built objects that are written in PHP. Some are packaged together in frameworks. Other times you’ll assemble them ala cart (a database abstraction layer here, a template system there). Sometimes building systems this way makes a lot of sense, but other times the overhead of divided tools makes for more work than it might be worth.

In Rails, they follow a mantra of “Convention Over Configuration.” With this in mind, Rails will follow industry conventions to make your job easier whenever possible. One example where you can see this in action is with page templates.

In Rails, if you have, for example, a BlogController and it has a method called list, Rails will automatically use the list.rhtml file inside of a folder called blog in your views folder. Not only that, but Rails will automatically pass on any instance variables you were using in the controller so that the view has access to them.

Now, when I am doing something similar in my own PHP apps, I have to manually instantiate the template object, manually pass references to any variables I know the view will be interested in and then manually tell it what template file to use. While all that manual code is pretty simple and easy to write, on even medium-sized apps it starts to take a toll on the leaness of the codebase.

This is one of the many reasons I like Rails. It will follow obvious conventions when possible but allow you to override the convention with a specific command; in this case to use a template file other than list.rhtml if needed.

Conclusion for part 1: PHP is just a language. Rails is a full-stack framework. PHP has lots of useful tools; they just don’t gel as well and usually require more configuration.

we explained how PHP is just a language, yet we never really talked about Ruby, the language in which Rails is written. Ruby is a fun and interesting language in its own right; however, it has gotten a lot more spotlight these days, specifically because of Rails. So, if you are using Rails you’ll be writing Ruby code, and now it’s time to compare some aspects of Ruby to PHP. For me, the biggest difference between Ruby and PHP is that Ruby is an object-oriented language throughout, while PHP’s object model feels more like an afterthought. In Ruby everything is an object, while in PHP most everything is a native variable type.

I’ve been using object-oriented design exclusively for a few years now, and while I continue to model my PHP web applications with objects, they can be very awkward at times. When this happens I’m usually forced to jump back to procedural programming to do things like iterate over a collection of objects. Iterators, by the way, are very cool in Ruby. For example, in Ruby I can do something like:

employees.each {|employee| employee.give_raise}

That .each statement lets me iterate over the collection and then use the reference between the pipes as a way to perform actions onto the object. In this case, giving each employee a raise.

In PHP few things are objects by default, including collections. Instead, there is a native array type and a bunch of functions that you can pass an array to that do something of interest. For small scripts this doesn’t bother me, but for my bigger projects it’s a real pain. Early on I even considered writing my own array object. I quickly let the idea die when I came to realize I’d have to pass out native array types to the various tools (like Smarty and a number of other PEAR Objects) anyway, as that’s what they knew how to work with.

So those are some of the biggest reasons why I’m starting to prefer Ruby over PHP, but this comparison still has one more part: deployment. What good is an app if you can’t put it onto a production server? In the final installment of this comparison we’ll look at the differences in deploying a Rails app vs a PHP app. See you then.

Tags : | add comments

PHP vs Java vs Ruby

Posted by admin on Friday Feb 15, 2008 Under PHP, Ruby on Rails

With Sun GPLv2’ing its Java software this week, a lot of focus is on the other open frameworks that have risen during the same era, and their comparative value in a post open source Java world. One such take is from well-known Sun insider, Tim Bray, who spoke at last week’s International PHP Conference in Germany.

Bray, who is Director of Web Technologies at Sun Microsystems, co-creator of the XML 1.0 and XML Namespace standards, co-founder of Open-Text, and contributor to the Atom Publishing standard (whew!) spoke in a presentation entitled “How to combine PHP technology with Java based on Enterprise Systems” (download PDF).

In the slide below, Bray outlines the basic advantages of each of these three platforms (or rather the two languages and one framework if you are scoring at home). In perhaps in a nod to his new employer, Sun, Bray totally omits any mention of .NET or smaller products like Adobe’s Flex/ColdFusion platform.

His idea, if you are able to take it on the surface only, is to rate your priorities of: 1) Scalability, 2) Dev Speed, 3) Dev Tools, and 4) Maintainability. In this highly generalized approach, you could theoretically pick your web application building language/framework based on only these priorities.

Tim weighs-in heavy on the maintainability side, and we’d tend to agree with him. To quote:

“Good apps, once built, tend to be in production for an astonishingly long time. Which means that they have to be maintained for an astonishingly long time. Which means that maintainability is important. There are a lot of things that go into maintainability, but I suggest that the biggies are object-orientation, MVC architecture, code readability, and code size.”

On the maintainability side Tim places Ruby on Rails out front. Quoting him again, Tim describes why RoR is in the lead here.

“Mostly because there’s less code. The fact that Ruby forces MVC on you helps too, also the fact that the templating and [Object Relational Mapping (ORM)] and testing and application code are all so tightly integrated helps. Bear in mind that we still don’t know how well Rails is going to work outside of the CRUD-centered greenfield app space where it shines.”

Tim’s metrics don’t really exist on a quantitative level nor are they based on any published statistics — just a very informed intellect and a privileged position. Obviously, additional parameters such as total cost of ownership and native security (PHP, we are looking at you) should also play a big role the decision making process.

As you can probably guess, in response to this presentation, the proponents of Java, PHP and Ruby are lighting the Internet aflame in defense of their platform of choice and at the same time nay-saying their fellow players. While very entertaining and sometimes educational to follow, not much is going to be gained from this bickering.

Bray concludes the presentation with the Rodney King-esque statement “One way or another we all have to integrate.”

The reality is that there are a great number of ways to hone-in on the language or framework choice for a web application. Many factors have to be considered and weighed against each other. The beauty of what we have today is that there ARE a great many choices out there, much more-so than even a few years ago.

The fact that open source options are being stacked up against the likes of Java and .NET, and have a similar levels of support is a blessing. Today, with the open-sourcing of Java, we have a new entry onto the field. Rather than exclude one or another, this arrival is going to make the open source web world, warmer, more sophisticated, and for better or worse, a little sunnier.

Tags : | add comments

Getting Information about Databases and Tables

Posted by admin on Friday Feb 15, 2008 Under MySql

MySQL provides a SHOW statement that has several variant forms that display information about databases and the tables in them. SHOW is helpful for keeping track of the contents of your databases and for reminding yourself about the structure of your tables. You can also use SHOW prior to issuing ALTER TABLE; it’s often easier to figure out how to specify a change to a column after you determine the column’s current definition.

The SHOW statement can be used to obtain information about several aspects of your databases and tables:

  • List the databases managed by the server:
    SHOW DATABASES;
  • List the tables in the current database or in a given database:
    SHOW TABLES;
    SHOW TABLES FROM db_name;
  • Note that SHOW TABLES doesn’t show TEMPORARY tables.
  • Display information about columns or indexes in a table:
    SHOW COLUMNS FROM tbl_name;
    SHOW INDEX FROM tbl_name;
  • The DESCRIBE tbl_name and EXPLAIN tbl_name statements are synonymous with SHOW COLUMNS FROM tbl_name.
  • Display descriptive information about tables in the current database or in a given database:
    SHOW TABLE STATUS;
    SHOW TABLE STATUS FROM db_name;
  • This statement was introduced in MySQL 3.23.0.
  • Display the CREATE TABLE statement that corresponds to the current structure of a table:
    SHOW CREATE TABLE tbl_name;
  • This statement was introduced in MySQL 3.23.20.

Several forms of SHOW take a LIKE ‘pat clause allowing a pattern to be given that limits the scope of the output. pat is interpreted as a SQL pattern that can include the ‘%‘ and ‘_‘ wildcard characters. For example, the following statement displays the names of tables in the current database that begin with ‘geo’:

SHOW TABLES LIKE 'geo%';

To match a literal instance of a wildcard character in a LIKE pattern, precede it with a backslash. Generally, this is done to match a literal ‘_‘, which occurs frequently in database, table, and column names.

The mysqlshow command provides some of the same information as the SHOW statement, which allows you to get database and table information from the shell:

  • List databases managed by the server:
    % mysqlshow
  • List tables in the named database:
    % mysqlshow db_name
  • Display information about columns in the named table:
    % mysqlshow db_name tbl_name
  • Display information about indexes in the named table:
    % mysqlshow --keys db_name tbl_name
  • Display descriptive information about tables in the named database:
    % mysqlshow --status db_name

The mysqldump utility allows you to see the structure of your tables in the form of a CREATE TABLE statement (much like SHOW CREATE TABLE). When using mysqldump to review table structure, be sure to invoke it with the –no-data option so that you don’t get swamped with your table’s data!

% mysqldump --no-data db_name tbl_name

If you omit the table name, mysqldump displays the structure for all tables in the database.

For both mysqlshow and mysqldump, you can specify the usual connection parameter options (such as –host or –user.)

Determining Which Table Types Your Server Supports

ISAM is the only type available before MySQL 3.23. From 3.23 on, MyISAM, MERGE, and HEAP are always available, and availability of the other types can be assessed by means of an appropriate SHOW VARIABLES statement:

SHOW VARIABLES LIKE 'have_isam';
SHOW VARIABLES LIKE 'have_bdb';
SHOW VARIABLES LIKE 'have_inno%';

If the output from the query shows that the variable has a value of YES, the corresponding table handler is enabled. If the value is something else or there is no output, the handler is unavailable. The use of the pattern have_inno% to determine InnoDB availability matches both have_innodb and have_innobase. (The latter form was used in MySQL 3.23.30 to 3.23.36 before being renamed to have_innodb.)

You can use table type information to determine whether your server supports transactions. BDB and InnoDB are the two transaction-safe table types, so check whether their handlers are enabled as described in the preceding discussion.

As of MySQL 4.1, the list of table types is available directly through the SHOW TABLE TYPES statement:

mysql> SHOW TABLE TYPES;
+--------+---------+-----------------------------------------------------------+
| Type   | Support | Comment                                                   |
+--------+---------+-----------------------------------------------------------+
| MyISAM | DEFAULT | Default type from 3.23 with great performance             |
| HEAP   | YES     | Hash based, stored in memory, useful for temporary tables |
| MERGE  | YES     | Collection of identical MyISAM tables                     |
| ISAM   | YES     | Obsolete table type; Is replaced by MyISAM                |
| InnoDB | YES     | Supports transactions, row-level locking and foreign keys |
| BDB    | YES     | Supports transactions and page-level locking              |
+--------+---------+-----------------------------------------------------------+

The Support value is YES or NO to indicate that the handler is or is not available, DISABLED if the handler is present but turned off, or DEFAULT for the table type that the server uses by default. The handler designated as DEFAULT should be considered available.

Checking a Table’s Existence or Type

It’s sometimes useful to be able to tell from within an application whether or not a given table exists. You can use SHOW TABLES to find out:

SHOW TABLES LIKE 'tbl_name';
SHOW TABLES FROM db_name LIKE 'tbl_name';

If the SHOW statement lists information for the table, it exists. It’s also possible to determine table existence with either of the following statements:

SELECT COUNT(*) FROM tbl_name;
SELECT * FROM tbl_name WHERE 0;

Each statement succeeds if the table exists and fails if it doesn’t. The first statement is most appropriate for MyISAM and ISAM tables, for which COUNT(*) with no WHERE clause is highly optimized. (It’s not so good for InnoDB or BDB tables, which require a full scan to count the rows.) The second statement is more general because is runs quickly for any table type. Use of these queries is most suitable for use within application programming languages, such as Perl or PHP, because you can test the success or failure of the query and take action accordingly. They’re not especially useful in a batch script that you run from mysql because you can’t do anything if an error occurs except terminate (or ignore the error, but then there’s obviously no point in running the query at all).

To determine the type of a table, you can use SHOW TABLE STATUS as of MySQL 3.23.0 or SHOW CREATE TABLE as of MySQL 3.23.20. The output from both statements includes a table type indicator. For versions older than 3.23.0, neither statement is available; but then the only available table type is ISAM, so there is no ambiguity about what storage format your tables use.

Tags : | add comments

Mysql table types

Posted by admin on Friday Feb 15, 2008 Under MySql

As of MySQL 4.1, the list of table types is available directly through the SHOW TABLE TYPES statement:

mysql> SHOW TABLE TYPES;
+--------+---------+-----------------------------------------------------------+
| Type   | Support | Comment                                                   |
+--------+---------+-----------------------------------------------------------+
| MyISAM | DEFAULT | Default type from 3.23 with great performance             |
| HEAP   | YES     | Hash based, stored in memory, useful for temporary tables |
| MERGE  | YES     | Collection of identical MyISAM tables                     |
| ISAM   | YES     | Obsolete table type; Is replaced by MyISAM                |
| InnoDB | YES     | Supports transactions, row-level locking and foreign keys |
| BDB    | YES     | Supports transactions and page-level locking              |
+--------+---------+-----------------------------------------------------------+
Tags : | add comments