Showing posts with label develop. Show all posts
Showing posts with label develop. Show all posts

Monday, February 26, 2007

Tips for software development /theoretical/

Well we all know how vast this topic is so I am going to be simple on this ;)

I will take two of my favorite sayings!



"Things should be made as simple as possible,
but not simpler." — Albert Einstein

Let us dig deeper on this thought! All people seem to have heard such sayings and react as "Well it is obvious you fool it is like you found a gold mine... fool!" when someone told them this wisdom. But why are they reacting so and why are they producing these enormous amount of software that is so over complexed?

Simple! They know it but never use it!
There is an other situation where dead lines play role and developers are forced to continue coding without re-thinking what they did wrong and fix, rewrite, rethink ... it and so on.

So what is my tip for such people!
Do not agree to short dead lines! Know what you need ... time money... and so on for the software you do. Don't calc it to the shortest possible way!
Calc it to best one available. By best I really mean doing something like this:

1. "Time for the project" /time you think is enough for the project to be build/
2. "Time for the project"x2 /double the time needed/
3. +50% /for the unexpected/

So now calc the time!
If the time for the project was 3months .... add x2 and then 50%... it basically happens to be x3
so it comes to 9 months for the project to be ready... but you see it will really be ready and will satisfy most of the needs of the purchaser.

This scheme will prove the most effective if you are serious about software and do build software the way it should be build ... SIMPLE AND ELEGANT!


I will not give more information on the topic as it is well written and much more explained in hundreds of pages all over the net and the globe ;)

I will just give you an example of why simple software wins!
Here is another wise thought!


"All things being equal, the simplest solution tends to be
the best one." — William of Ockham


All sounds very logical right :)
William and Albert told it!

If you found this refreshing of thoughts interesting then I really entered your mind and found a sweet spot... but the most important thing is! YOU REALIZE THE IMPORTANCE OF ALL THIS!

I recommend you read the book of 37singnals - Getting Real
It will reveal most of the things I didn't mentioned here but you already are thinking for. You can buy their book or just read it online at their site http://www.37signals.com/
Yes those are the RUBY people ;) they are the founders of Ruby On Rails.
So they know what they are talking about after being quite successful over time.



I would like to finish with this wise words again ;) so think over them whenever you build software... and in general something that people would use.

"Things should be made as simple as possible,
but not simpler." — Albert Einstein


Прочети цялата статия...

Sunday, February 25, 2007

Ease your recursion

Ever wanted to have an easy way of building a recursive tree ?
Or something like that ?
Or even without understanding much of recursion or always thinking how was this done and so one ?

Well I eased your life a bit ;P



<?php
/**
* Function that builds a category tree with recursion
* (it selects only id, [your specified field] and parent_id
* from the selected table)
*
* @param string $spacer
* @param string $table_name
* @param string $field_name
* @param integer $start_id
* @param string $link
* @param string $request_param
* @param string $link_style
*/
function buildRecursionTree($spacer = '>>' , $table_name ,
$field_name , $start_id = '0' ,
$link , $request_param ,
$link_style) {
global $db;

$sql = "SELECT `id`,`$field_name`,`parent_id`
FROM `$table_name`
WHERE `parent_id`='$start_id'";
$result = $db->query($sql);
while (list($id,$name,$parent_id) = $db->fetch_array($result)) {
$spacer_next = " ".$spacer;
?>
<?=$spacer?>
<a href="'<?="$link?">?<?=$request_param?>=<?=$id?>'
style='<?=$link_style?>' >
<?=$name?>
</a>
<br/>
<?
buildRecursionTree($spacer_next , $table_name ,
$field_name , $id ,
$link , $request_param ,
$link_style);
}
}
?>


And now some sample usage ;)


<?
$spacer = "<img src='images/arrow.png' border='0' />";
$table_name = "categories";
$field_name = "name";
$start_id = "0";
$link = "index.php";
$request_param = "category";
$link_style = "color: #000000; font-family: arial;
font-size: 11px;
text-decoration: none;";
buildRecursionTree($spacer , $table_name , $field_name ,
$start_id ,
$link , $request_param , $link_style);
?>


Well easy enough huh !
See the sample result yourself ;)

Прочети цялата статия...

Wednesday, February 14, 2007

Ruby - the power of simplicity

I expect that most of you have already heard of RUBY.
If not! Well RUBY is the new hot programming language... as always new doesn't really mean it has been released yesterday but it is a newcomer to the world of programming language popularity.

Why is ruby hot?
Well RUBY is all about simplicity.
You know when you switched from C or Java to PHP when developing web based applications and saw how PHP deals fast and easy with web oriented stuff... so does RUBY.
Actually RUBY has been planed all around web application development. It focus on simplicity and elegance. It is a mix between PHP,PYTHON and maybe JAVA. You know! Everything in RUBY is an object! Yes! That is true :) everything is an object so for the object oriented developers it is really a good one ;)
But what is a programming language without the TOOLS.

RUBY ON RAILS
Ruby on Rails is a framework that will help you deploy everything almost out of the box. It is really made simple, elegant and very very powerful!
The actual idea of Ruby and Ruby on Rails is to enable the developer to focus on the actual problems ... what the user see and get... not the background stuff and all the silly little problems but the actual problems and solving them.

If you think I am over happy with ruby and I talk this because I am a ruby developer you can see the statistics at TIOBE
Yes that is right :) RUBY has gained an enormous popularity recently and stepped 10 positions above. Eventually I should tell you that the trends for 2007 are like this:
1. Microsoft Vista entering slowly on Desktop PC
2. Ruby gaining vast popularity among web developers
3. ...

Hmmm sounds good right ? :)
So to make you over happy I will tell you more on Ruby on Rails.

Ruby on Rails is the software you need for ruby development.
You remember when I said about making something almost out of the box ?
Well ruby on rails enables you to have UNIT testing on the fly... database stuff that generates by default and you know it is really a good software. The people from 37signals have really done again a great job with this peace of software.
What really makes people like RUBY and RUBY ON RAILS is that 37signals designed Rails with simplicity, elegance and POWER in mind. All you need to setup for the proper development of an application is made simple and powerful and you can come up with UNIT TESTS (for example) in the blink of an eye... it is made automatically for you.

But enough talking you can see more about RUBY on http://www.ruby-lang.org/

Прочети цялата статия...

Saturday, February 03, 2007

Basic SEO - steps to improve your SERP

Well I've been asked to write about SEO.

For those that don't know what SEO is it is the short of Search Engine Optimization. But what does this really mean ? It means that if a good SEO is in place your web page will display on top of the results in some search engine for a certain keyword.
For those that don't know what SERP is ;) it stands for: search engine results page

Sounds like interesting stuff?




Well here are a few steps to actually achieve this:

BASIC

1. Use H1 html tag to display your title

2. Use H2 for the subtitle

3. Keywords meta, title, description, url, h1 and h2 tags should have something in common if they are the same the satisfaction will be 100% ... so the use of a term like "findacar" for example if used right in all the stuff of the web page shall bring you very good results in search engines with the search term "FIND A CAR"

4. Do bold or strong whenever possible ... Google thinks it is important and raises results for your page for the tagged word

5. Do not use a lot of keywords in the meta

6. New content is very positive... a forum on your site shall bring enough new data for the day

7. Making your sign in the forums at the bottom of your post to be a link at your site will both increase traffic(which is the most powerful SEO) and will give a link to your page(SITES THAT LINK TO YOURS IS CONSIDERED KEY FUNDAMENTAL IN MOST OF THE SEARCH ENGINES FOR DISPLAYING... ESPECIALLY GOOGLE)

8. Don't waist your energy on giving links off your site... it will decrease your overall SEO... especially the Google results for your site

interesting

The GOOGLE Page Rank algorithm is LINK based!
It will place you more on top if major PG(Page Rank) sites give a link to yours. So a fundamental concept is to have more inbound links (to your site) ... at the opposite side external links (on your site pointing to an other site) will decrease your PG.


ADVANCED

1. The Google algorithm is strongly working depending on links... a good practice is the management of your own links(your inside site navigation and so on links) too!
The very first thing is: NOT HAVING BROKEN LINKS

2. NOT HAVING A TREE STRUCTURE OF LINKS THAT THE CRAWLER WILL CRAW AND END ON A PAGE WHERE IT CAN'T MOVE FROM IT... EXAMPLE NOT HAVING LINKS THAT ARE POINTING BACK TO YOUR HOMEPAGE

3. Having as much links that the crawler needs to crawl ... so not only to have on all the pages the home link but also many others so that the bot stays on your site much longer and finds more info... it is questionable the methods of how the crawler really works but this is tested stuff believe me!

EXPERT

If not used right this might be considered gray or even BLACK hatting so please be ethical,moral and so on on this one! I DO NOT ENCOURAGE THE USE OF ANY BLACK HAT STRATEGIES!!! I am writing strongly white hat strategies which are 100% acceptable from the SEARCH ENGINES policy and terms of service and so on...
This tips are not straight forward so it might be a good idea to check wikipedia or search Google for ideas about this.

1. Making use of the SLASHDOT effect

2. Making use of the DIGG effect

3. Making use of GOOD INFORMATION

This is the most important one!
IF YOUR SITE HAS VALUABLE CONTENT THERE IS A 99% PROBABILITY OF PEOPLE LINKING TO IT AND MAKING ENORMOUS AMOUNT OF TRAFFIC WHICH IS OUR MING GOAL!!! WHY DID I PUT THIS HERE? WELL PUBLISHING AND INTRODUCING INFORMATION IS NOT SO EASY AND IS ACTUALLY THE MOST TIME CONSUMING AND HARD CONCEPT OFF ALL. MAKE SURE YOU WILL INTRODUCE THE INFORMATION IN AS MORE HTML-ALIZED VERSION TO THE AUDIENCE AND MAKE IT SHORT AND PAGINATED. ALSO IF YOU SKIPP MOST OF THE JAVASCRIPT AND FLASH EXTRAS IT WILL BE POSITIVE FOR YOUR SEO. MAKING W3C VALIDATIONS WILL ALSO BE VERY USEFUL AND WILL MAKE POSITIVE SEO RESULTS!




Making more simple and html-lized as well as friendly and more standard compliant sites will be the most powerful SEO from the view of the development process. The next thing is introducing valuable information!

Hope this one article was useful!




Want to try your SEO skills ?
Wonder how ?
Here is a link to a contest where you can try and will a small price ;)
http://bgwebmast.org/


Прочети цялата статия...

Monday, January 15, 2007

3 basic files to work with

I haven't posted anything "code like" for some time huh ;)
Well now is the time to actually dig up some code!



I thought a lot about the topic to write on and it will be really a one for starters.
These 3 files I will show you are the solid foundation of all my projects. A project should have these files always. If a project does not contain those files or files like the one I will give you then it has a major drawback or is just too small so it doesn't actually needs it ;) but you need almost 99% of the time files that serve this purpose. So enough with the initial bla bla bla :) nets code ;)


I will follow this schema:

1. Describing why it is good to have it
2. Actual CODE
3. Tips and other options to this





NAME: config.php
1. Description

This is a configuration file which will give you the control over the server. As a server I mean that you will be able to tweak the php.ini file as you like. This file represents a large number of ini_set() function which will temporary change the scripts behavior. Changing the php.ini config or the scripts behavior is a big plus when developing a project which will be hosted on a server which is out of your touch and for example you can't touch the php.ini file to say hide the error reporting or so on. So having this allow us to change the preferences of PHP as expected by us, the developers! Take a note that some of the directives might not be changed so don't expect always to have a full control over the php.ini!

Besides PHP configuration this file represents a central unit for defining the PATH of our application or the USERNAMES, PASSWORDS and so on of say, the DATABASE server. So have a look a it!

2. The CODE


##################################################################
#
#===== CONFIGURAION FILE =====
#
#=================================================================
#
# php.ini directives
# database constants
# path constants
#
#=================================================================
#
# PHP 5.2 version
#
#=================================================================
#======= created by Yavor Ivanov | email: =======#
#=================================================================
##################################################################
//////////////////////////////////////////////////////////////////


#===== PHP.INI DIRECTIVES
ini_set("output_buffering" , 0); // OUTPUT BUFFER
ini_set("safe_mode" , 0); // SAFE MODE
ini_set("expose_php" , 0);
ini_set("max_execution_time" , "120");
ini_set("max_input_time" , "60");
ini_set("memory_limit" , "16M");
error_reporting(E_ALL | E_STRICT); // ERROR REPORTING
ini_set("display_errors" , 1); // DISPLAY ERRORS
ini_set("display_startup_errors" , 1);
ini_set("log_errors" , 1);
ini_set("report_memleaks" , 1);
ini_set("html_errors" , 1);
ini_set("error_log" , "syslog"); // ERROR LOG
ini_set("register_globals" , 0);
ini_set("magic_quotes_gpc" , 0);
ini_set("magic_quotes_runtime" , 0);
ini_set("file_uploads" , 1); // FILE UPLOADS
ini_set("upload_max_filesize" , "10M");
ini_set("session.use_cookies" , 0); // USE COOCKIES
ini_set("session.auto_start" , 1); // SESSION AUTO START
ini_set("session.cookie_lifetime" , 0);
ini_set("session.gc_probability" , "1");
ini_set("session.gc_divisor" , "100");
ini_set("session.gc_maxlifetime" , "1440");
ini_set("session.cache_expire" , "180");
ini_set("url_rewriter.tags" , ""); // URL REWRITER
#=================================================================


#===== DATABASE CONSTANTS
define("DBHOST" , "127.0.0.1");
define("DBUSER" , "username");
define("DBPASS" , "password");
define("DBNAME" , "database");
#=================================================================


#===== PATH CONSTANTS
define("BASE_PATH", str_replace('\\', '/', dirname(__FILE__)));

define("CLASSES" , BASE_PATH."classes/");
define("WEB_ROOT" , BASE_PATH."/web_root/");
#=================================================================
?>



3. Tips and other options to this

There aren't much words to be put in here for this piece of code but we can say that you are free to add some more directives or define more constants at your desire and need. The tricky thing you can do here is to put as much configuration options as possible so your team mates knows that they only need to go in here and change the desired thing.





NAME: session.inc.php
1. Description

Basically this is a file to be included always at the start of every file. Why? Because it starts the session every time and keeps it running trough the whole application and also protects from hijacing. But let us see the code!

2. The CODE


session_start();
session_regenerate_id(true);

// if the user is just accessing the server his session
// is empty so BUILD a unique hash and put it in
if (empty($_SESSION)) {
// md5 or sha1 might be used for increased security
// but it might become slower
$_SESSION['hash'] = $_SERVER['REMOTE_ADDR'] .
$_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_PORT'];
} else{
// md5 or sha1 might be used for increased security
// but it might become slower
$hash = $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] .
$_SERVER['REMOTE_PORT'];

// if the hash is different from the original one build
// when first accessing the SERVER
// there might be a second user who might be a hidjacker
// so we destroy the SESSION !!!
if ($_SESSION['hash'] != $hash) {
session_unset($_SESSION);
session_destroy();
session_start();
session_regenerate_id(true);
$err = "Sorry there was a problem accessing the page!";
exit($err);
}
}
?>



3. Tips and other options to this

So what you see here is changing the session on every click of the user ;) why? Why not :) Every switching of session id can make our un-welcomed harmful user have a hard time. Beside in php5 regenerate_id() has a param of true which will destroy our previous session. Also making a unique hash of some info about the user protects us from hijacing. You can do the hash more complex and unique :) just play with code a bit it is well documented and easy to read :) at least my team mates and I think so.




NAME: database.class.php
1. Description

What you will see in the source is a PHP 5 class which will connect automatically to the database, when you create the object and the cool thing about this class is that it will execute every single query as a custom method... what is so cool about it :)
Well if you decide that you will use postgres sql you will not change all the mysql_query with pg_query for example but instead you will change just the class methods ;) cool huh! And I made a special param called DEBUG when you give it TRUE it will print your query ;) so you can latter paste it in for example in phpMyAdmin or something of the sort and look at what is actually causing trouble and so on ;) yes you can do it some more advanced like putting error logging and so on so this is the reason you can use the class and upgrade it ;)

2. The CODE


##################################################################
#
#===== Database Interaction Class =====
#
#=================================================================
#
# Written for MySQL database server
# Easily modified to work for a different SQL server
#
#
#=================================================================
#
# PHP 5.2 version
#
#=================================================================
#======= created by Yavor Ivanov | yavor.xenium@gmail.com =======#
#=================================================================
##################################################################
//////////////////////////////////////////////////////////////////


class DBI {
private $init_db;


public function __construct() {
if ( !isset($this->init_db) ) {
$this->init_db = mysqli_connect( DBHOST , DBUSER , DBPASS , DBNAME );
}
}


public function __destruct() {
mysqli_close();
}


//============================================================


function query($sql , $DEBUG = false) {
if ( $DEBUG == true ) {
print "";
print "SQL: ";
print "
";
print $sql;
print "
";
print "
";
}
return mysqli_query($sql);
}


function fetch_array($sql) {
return mysqli_fetch_array($sql);
}


function query_and_fetch($sql , $DEBUG = FALSE) {
$result = $this->fetch_array($this->query($sql));

if ( $DEBUG == true ) {
print "";
print "SQL: ";
print "
";
print $sql;
print "
";
print "
";
}

return $result;
}


function num_rows($result) {
return mysqli_num_rows($result);
}


function get_last_id() {
list($value) = $this->query_and_fetch("SELECT LAST_INSERT_ID()");
return $value;
}


}
?>



3. Tips and other options to this

So as I said the cool thing is that you can actually change databases very easily with few mods of the class. Also adding error logging might be a good idea or for example you can make automated escapes of variables or just another method like EscapeParam for example ;)
Use you imagination here and automate as much as you can to ease your work! Notice I use mysqli so don't expect this to work on php4.

There are a lot of object persistent classes and abstract ones but this is something that is easily understood and is something that you can tweak around :) most of the persistent/abstract classes aren't very short and need time to go into the code while this is short and useful the other alternative (I mean the persistent/abstract classes) are much more powerful and offer much more things ;)




Well with this article I demonstrated the basic files each application should have. I hope those of you who didn't knew where to start now know the entry point and will start smooth ;)
The demonstrated here CODE isn't the best! Come on! Spare me all the critics you might have for it... it is far than a complete solution. The targeted audience isn't experienced programmers which know everything while sharing some ideas might enlightened them, it is new ones that could not find the path and I try to give them what is considered good.


So I hope you will find the CODE interesting and you got idea what to do with it so start the codding, have fun with it and.... CODE it secure ;)

Прочети цялата статия...

Monday, January 08, 2007

PHP Security Tips

A lot of programmers out there use PHP to do their every day tasks but a lot of them are not very aware of SECURITY issues at all. So this article is intended to those users who actually are not very aware of the security in PHP development. I will provide some basic overview and run through the most common problems and their solution and actually I will tell you some pretty cool tricks so you don't worry about your applications security. So shall we start ?

Short list of security issues:
1. Not escaping user input fields
2. Not escaping SQL queries
3. URL parameters hack
4. Giving direct access to files
5. Configuration of the web server



First of all I shall say that this article will not make you aware of all the problems you might get when fighting with crackers and there are plenty of other hacks that will not be covered here... but this list of SECURITY issues shall be more than enough for your web site to be stable and secure. And second - a completely secure system is virtually impossible.

This is what I call a list of basic security issues which most of the unexperienced web developers are unaware of.

1. Not escaping user input fields
and 2. Not escaping SQL queries

Escaping of a string means the obscuring of the special symbols like HTML or SCRIPT tags which provide native code execution or something of the kind. So escaping means if we put our PHP code in a post on a site which has escaped our post the code wont execute.

Well as you might already think not using this method for protecting your site is a very serious issue. Imagine this web page where you can post a comment. Imagine you can make in your post a whole new page. Well lets just limit our imagination to a JavaScript for redirection. So if a user posts this JS like a comment and all the symbols aren't escaped we will end up with a page which will redirect to somewhere else... so a big minus for our users and probably they will not come back to our site because the HARMFUL user already did his job well to bring our site down. And just in case this seems not so bad for you imagine putting a piece of code which will execute and delete our database or just bring our web server down (without redirecting).

A simple code use that will eventually prevent the closing of an html tag:


//user submited text is: I will brake you code with this " symbol
$str = $_POST['user_submited_text'];

echo addslashes($str);
// Outputs: I will brake you code with this \" symbol


Addslashes function will escape the ' , " , \ and NULL symbols by putting a dash in front of them. Actually addslashes will be more effective for our second issue - SQL queries.
SQL queries are vulnerable to the so called sql injection. It means that you want ot submit a qeury with a value that is submitted by the user but instead of standard WORD he puts a whole string that makes your query end, begins a new query build by himself then ends his query.
And guess what might his query be? Maybe "DROP dbname;" will be appropriate which ofcourse isn't a good query and will drop our database.

So a really useful thing in all the cases is to just use not addslashes but some other function which will escape most of the harmful symbols like < > ? ; " ' and so on.
So a good function to use is htmlspecialchars, mysql_real_escape_string or build a custom one.


3. URL parameters hack
This issue is connected with what the most of the normal web surfers don't really see.
The GET parameters in the URL. Normally these GET params are of great help for the web developers so they can process information across multiple scripts but if those scripts are badly written a potential security hole is open and a cracker might use this against us.
See this example of telling the script to create a page.
http://example.com/pages.php?action=create
Let us say this script gives you control over your pages and you can create, edit and delete your pages. Well normally the delete process would be something like this:
http://example.com/pages.php?action=delete&id=2
Well this will tell the script to delete page with ID = 2. But what if the user doesn't pick one of the links with his assigned pages IDs but puts like ID = 2105. Well he might just got one of our users hate us for deleting his page. So you should be very careful about the usage of URL GET PARAMS in your application. A method to protect is to double check everything especially user rights. I can't give you a code example to protect against this cause it will depend on what you have programmed but you can use isset(), empty() and the $_SESSION super global array to prevent some of the bugs you might INCIDENTALLY leave. Cause you know no body is perfect.


4. Giving direct access to files
Another issue is the use of require_once("script_name.php");.
What is wrong with this? Actually nothing :)
You include a file which will provide certain functionality in another file which you have checked that the user has been logged in and so on... security security security.... but what if the user access this file directly and skip all the checking that were made in the other file?
So providing access to all your script files is a bad idea.
you can always put tons of code in them to make them not execute but!
I said something about tricks right ?
Well most of the web developers use htaccess files to protect files from direct execution or as I said tons of code includes which serves the same purpose. Well here is the tricky part.
While developing your web application make a directory like WEB_ROOT where you will put all the visible parts of the site like all your HTML files, images and so on. The scripts you include one level up in the tree. So you have all the scripts in the ROOT folder and all the things that the users will see in its subfolder named WEB_ROOT. In the WEB_ROOT include just one script file (mostly this is the index.php file) which will control the scripts that aren't directly accessible. And when you deploy your web site just make sure your domain name will load the WEB_ROOT folder.
Why this is tricky?
- you don't need many files for access control
- you don't include unnecessary protection code in your files
- PHP works with the file system (so it can access the files with ../ but HTTP doesn't work the same way and ../ wont bring you the content of the ROOT folder).


5. Configuration of the web server
Many problems come from miss configuration of the web server especially the php.ini file which is responsible for the PHP module of your web server.
While in general this is a custom process you can do the following to protect.
1. Make a config file to include in your project if you don't have/use one
2. with ini_set set some of the php.ini directives so they work as you expect
3. turn error_reporting off when you site is in production state not development
4. and at the end always recommend to turn php into safe mode




I say again that this is far alway from full list of SECURITY issues. But this shall be more than enough if you comply with it to provide your application a stable and secure environment to run.

There is a lot about this topic I will be glad to explain if you leave a comment and ask politely! But I will have to ASK those of you who will find my article unsatisfied to not submit their hate here!

As I used to say: "Love your code, have fun with it and don't hate it" ;)

Cheers!

Прочети цялата статия...

Sunday, January 07, 2007

IE7 Web Developers Nightmare

Internet Explorer 7 has kicked in at last on all MS Windows OS running PCs because of the fact M$ decided to force it's users to migrate through update. Well actually there isn't much wrong with this but IE7 was supposed to comply more with the standards what in fact isn't true.
IE7 is a night mare for most of the developers that try to comply with standards for crossbrowsing.
I recently needed to rewrite a web site so it works on firefox too... and the surprising element was that when testing the new and the old site on IE7 I found out that many things does not function as expected and "not function as expected" isn't the right word for it, it was more a question of working at all.

I found that submiting through JavaScript has some pretty uncool things which I don't actually blame IE but some functions did not work when not passing all the parameters and so on.
And the MOST killer thing was the DISability of IE to submit data through "input type img" which actually was the whole sites data... I don't actually blame the programmers that they did it so but IE for not keeping with standards again.

So actually with IE7 we come to a new era of "web developers nightmare" as it will require BAD and maybe not so BAD web sites to be rewritten and this with crush some of the small companies business.

And a final TIP from me! Try avoiding writing JavaScript without testing it 100% on all of the major used web browsers like FireFox, IE7, Opera and Safari.

Just to have a clue:
According to W3C the web browser market share of IE7 for the previous month is: 7.1%
and for IE6 is: 49.9%

So with a bit of analyzing the situation and the facts as well as doing some math we can say that IE7 will show a market share of about 60% according to W3C... which isn't the best picture for us the devs.



Have fun with you code and don't hate it :) hate the things that don't comply to the standards...

Прочети цялата статия...

Saturday, January 06, 2007

Use of Model View Controller

Model View Controller also known as MVC is a great way to do development. But what actually is MVC? It is not a tool or software that you can actually buy... well yes you can buy it and you can name it a tool but I will not speak of those made by others but for those hand made by you. OK so what was MVC? MVC is a self made FRAMEWORK. It's idea is to have TREE TIER SOFTWARE DEVELOPMENT.
Those tree layers are Model, View and Controller. In this article I will write mostly about the CONTROLLER and leave you space to think about the other elements while I will try to give you some basic idea about them too.


step 0. We start building some project and we don't know where to start from. Obviously we should start with some configuration file right? That is good... but don't forget the initial planning it is way more important but we skip this now :) After building some config file we need an index.php file which we will enchant with the power of MVC methodology.

So a basic step 0 is to make a config file and index.php with some basic design and idea.

step 1. The next thing we will do is to build our CONTROLLER. It is responsible for controlling the overall process of our application. So it needs to comply with the following things:
- handle URL requests
- process requested information to and from the layers
- handle loading of classes

This is our very basic form.
/we skip some other code that should be there keep that in mind/


Here it is in PHP code:




##### ..:CONFIG FILE:.. #####
require_once("../config.php");
##### ***CONFIG FILE*** #####

##### ..:AUTOLOAD:.. #####
function __autoload($class_name) {
$dirs = array('/experts/','/experts/db/','/experts/user/', '/experts/question/');
array_push($dirs,'/experts/exceptions/');

foreach ($dirs as $dir) {
$classfile = CLASSES . $dir . $class_name . '.php';
if ( file_exists($classfile ) ) {
require_once ($classfile);
}
}
}
##### ***AUTOLOAD*** #####

##### ..:CONTROLLER:.. #####
if (isset ($_REQUEST['module'])) {
require_once(MODULES . basename($_REQUEST['module']) . ".php");
} else {
require_once(MODULES . 'default.php');
}
##### ***CONTROLLER*** #####




So what you see in this code is that we include in the first place the CONFIG file and this shall be clear why. The second thing is making use of AUTOLOAD function in PHP5 which finds for us the needed class and we don't care about including classes we made into the files (modules) we write.

And then the actual CONTROLLER which just looks a GET parameter and sees if its name build with .php exists in the MODULES folder and if yes it loads it... if not it loads a default one.

This is the INDEX.PHP file code... it needs to have some design or some VIEW implementation which you can see how to achive in the bottom (well actually you will have to read a bit more off this site but don't bother I might write about this another time)

step 2. Is the Model... we will call these MODELS - MODULES.
These MODULES work in the following way:

They are loaded by the CONTROLLER and they serve a specific functionality like login/logout. In this Module we work with the functionality (the classes) we wrote. And this is it.
We might do this to work directly with the VIEW as the following code:




// Proccess with user input if given
if (isset($_GET['action'])) {
switch ($_GET['action']) {
case 'login':
require_once(STATIC_MODULES."login/handle_login.php");
break;
case 'logout':
require_once(STATIC_MODULES."login/handle_logout.php");
break;
}
}

// Display the needed Smarty tpl
if (isset($_SESSION['auth'])) {
$user = unserialize($_SESSION['user']);
$user->loadStats();

$smarty->assign("button" , '<a href="index.php?action=logout">
<img src="button logout.png" style="border: 0px;" />
');
$smarty->assign("username" , $user->getUsername());
$smarty->assign("title" , $user->getStats()->getTitle());
$smarty->assign("points" , $user->getStats()->getCredits());
$smarty->display("STATIC/login/login.tpl");
} else {
$smarty->display("STATIC/login/login_form.tpl");
}




The Module just looks after a PARAM to be sure if it is set then process to other modules if necessary ... then it unserializes an OBJECT of the user from the SESSION loads the user info and process the needed info for the VIEW (which is SMARTY template engine).

step 3. The VIEW is already mentioned it is just a TPL file of SMARTY ... for more info about this Templating Engine look at smarty.php.net or just google it for more information. In few words the VIEW is a TPL file which has in it those {$variableName} tags which by parsing this file they are replaced with values that we assign through the MODULES (MODEL).



So for all of you PHP geeks which were not known to MVC I think this is enough to see the power you get from this framework... if you don't see it I will mention some things:

- You get a FRAMEWORK for every project you build to use
- It is easily to upgrade and use
- You don't need to touch the files of your framework most of the times only the CONFIG file and then just start building the MODULES
- You easily will redesign the site because of the templates you use
- You write without caring about includes paths or other stuff
- and if you write this good (not that this isn't good but this piece of code is not what it is now at the project we have used it... yes this was working code :) now it is more advanced with more lines of code and complexity but this is its main idea) you will develop you projects twice as fast as you usually do and believe me when I say YOU GOT THE POWER OF Objects AND Templates AND Re-Usability OF CODE and this is what most programmers have difficulties to achieve.

But YES this isn't a topic that I can cover in a hour or too just like this and yes I am not good at large scale Articles which cover future and history and so on so just look at what wikipedia has to offer about this topic... I'll ease you with this direct link to MVC at wikipedia.

I hope I have given you the first steps and thoughts about building your own MVC whether in PHP or some other programming language.
Have fun!
And remember not to hate your code but to have fun with it ;)

Прочети цялата статия...

Friday, January 05, 2007

Basic Recursion

I found out that many programmers that are not academic educated but self learners don't know recursion. And this is something that might safe your life pretty fast sometimes ... so I will drop a few lines about it and why use it.


Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own definition. The term is also used more generally to describe a process of repeating objects in a self-similar way. For instance, when the surfaces of two mirrors are almost parallel with each other the nested images that occur are a form of recursion.
/description from Wikipedia/

I actually find pretty confusing the example with the mirrors for someone who is hearing for the first time about recursion. So I will give one from me:
"Drawing a tree structure from the folders and sub folders of your computer hard drive is made with recursion."

So as I expect my audience to be people from the IT sector or at least people generally known to software or programming at least at a basic level I will give an example of this with web based category navigation.

So we have something like 1 is the root of 2 and 3.
And 2 is the root of 4.
It looks like this:
1
|-2
_|-4
|-3


php code example:




// Making the function to draw the tree ***RECURSION IN MIND***
function tree($id='0',$spacer="          "){
$query = "SELECT * FROM categories WHERE parent_id='$id'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo $spacer.'img src="images/folder.png" border="0" /> '.
$row['title'].'   '.
'a href="index.php?module=ADMIN">'.'add'.'/a> | '.
'a href="index.php?module=ADMIN" style="font-size:9px;">'.'edit'.'/a>
';
// The RECURSION
tree($row['id'],$spacer."          ");
}
}

// Calling the function
tree();





This is old code that I posted accidentally without looking at it that it is not recursion sorry about this... I will leave it in case someone find it useful ;)



public function navigation($id) {
$navigation = '';

$this->initdb();
$sql = "SELECT `id`,`name`,`description`,`parent_id`
FROM `category`
WHERE `id` = '$id'
LIMIT 1";

$res = $this->db->query($sql);
$row = $res->fetchRow(MDB2_FETCHMODE_ASSOC);
$navigation .= $row['name'];
$parent_id = $row['parent_id'];

while($parent_id != 0) {
$sql = "SELECT `id`,`name`,`description`,`parent_id`
FROM `category`
WHERE `id` = '$parent_id'
LIMIT 1";

$result = $this->db->query($sql);
$row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);

// REVERSE THE BUILD
$navigation = $row['name'].' > '.$navigation;

$parent_id = $row['parent_id'];
}

//$this->checkPearError($result);
return $navigation;
}






I hope that the example is clear to understand... for those with PHP and MySQL knowledge it shouldn't be a problem even if they never used the MDB2 pear package.
Recursion is very useful in those situations where you need repetitive work.

This is working code from a project I participate in and this chunk is written by me :-p
So yes it actually works ;-)

So I hope I gave light on this topic!
Good night folks.

Прочети цялата статия...

Thursday, January 04, 2007

Team Software Development

This article is about Software Management and especially about the working process of developers. It should make light on the way team work is done and show how it could be made a lot faster, easier and even fun. I will try to explain why some people think their way works for them but in fact they were very wrong and migrating to this way of software development is exactly for them.

First I want to really say that I am really for Open Source technology but I really appreciate the commercial things that just works... what is written well is written well and there is no doubt when people are happy with it and use it. So this sentence was a kind of "I want you to know me" so you know I am judging from a neutral side.


I will start with a real life example at my job again!
We do software development like this:
1. accessing FTP server
2. downloading content
3. writing code to files
4. saving files
5. looking at modifications

Well I expect some people to say that this is a normal software development stuff and there is nothing wrong with it but let us see this:
1. accessing FTP server
2. downloading content
3. writing code to files
- another one is writing code to the same files
4. saving files
- overwriting each others code
5. looking at modifications (yours or of your colleague or the worst case of something between)
- some users are looking at changes you do... whether harmless ones or not so harmless

Well you see the picture!
This type of software development is not good for any one.
I will not go into details about it you saw the picture and you shall think about it!

Then I shall show you a real software development model.
The tool or software which is used in it is called SUBVERSION or SVN.
It is the successor of Concurrent Versions System (CVS) but it has some improvements. So what is so cool about this SVN you ask. Well first of all many people write code and every one is made aware of the changes. Then you develop software with a whole bunch of version control things that ease your life. Well let me try to summarize it:

SVN is a Version Control System that keeps track of all work and all changes in a set of files, typically the implementation of a software project, and allows several (potentially widely separated) developers to collaborate.

The thing about this open source software is that it really works and helps. I will not go into details about how it is used or implemented I want to just show you the benefit of switching to it. SVN doesn't only make you aware of file changes. It allow programmers to lock files, merge changes, comment what they made with the file... and so on. Also SVN is most of the time a separate server on which you develop so users don't have to see your changes in real time. Also a cool thing is that you have a structure of versions that is tree like. When you build a version that is stable enough you can make it go up into the so called branch where you can then just copy this to the server where you want to deploy the project or if the host and develop server are one and the same you can just relink to the newest branch and hey! We got our site updated.

SVN has one more cool thing!
TRAC - an open source, minimalist and web-based project management and bug-tracking tool

Trac allows hyperlinking information between a computer bug database, revision control and wiki content. It also serves as a sophisticated web interface to the subversion version control system. The web front end presentation of Trac is handled by the ClearSilver template system.

Cool huh!

So if you find this useful and actually tried it please let me know your opinion!

Nice hacking!

Прочети цялата статия...

Wednesday, January 03, 2007

IDE vs Editors

In this article I will try to obsolete any believes that standard text editors or even the more advanced ones are not only bad but evil!



First you might want to look just at the above pictures.
What you will prefer to write on?
Maybe in bed I will want the Book 'cause it is better than a personal computer but is it really faster than it? What if I make a mistake? I'll have to rewrite it... on the PC I will do undo or just retype it. Hmmm clever isn't it?!?!

Well the same basics are there for IDE vs Text Editors.

I will give a real example again. Consider the following situation at work.
You have a server where you host the project a boss tells you to "LOGIN" to it and make some changes... ok there are some great editors like JEdit which have many plug-ins and can have a build in client or what so ever... so OK. Then you need to, let's say find the bug in the design. What a horrible task. Yes you will need to look at all the spicy code in there an fix some unclosed tag. Then you need to add some functionality and can't remember the PHP function name for striping some characters... oh my!


I think you already got the picture!
You are faced in the worst case scenario with lack of highlighting, tag completion, ftp client ... and so on.

With an IDE(Integrated Development Environment) you got all this if not more.
Even in the best case scenario the TEXT EDITOR will lack one of your needs like say SVN client. But with an IDE you got it all there build in or with plug-ins that just work with the environment.

My boss told me that using an IDE leads to some BAD habits like not remembering all the function names or like using a function that you don't actually know what it does. But that ain't true.
IDE is giving you all the details and corrects your silly mistakes... and all the experience you will gain just by writing and looking at the code is enough to make sure you know what you are doing. An IDE is the Swiss knife of a modern DEVELOPER.

There are some good choices like Eclipse and ZDE (Zend inc) for PHP for example.
And there are plenty more... for other languages too... both free and paid.

But what I really wanted to say is that using a text editor leads to bad habits like writing text instead of code. This is not right to do and shall not be tolerated within the mind of developer.
A real developer should know what he's doing and just use the tools to be more productive, not waste time on silly mistakes or facing trouble with some software or hardware issues that ain't he's work.

So what you say ?
I will appreciate if you drop some comments so I know I provoked your mind to think about the topic... or just that you support me ;-)

So have fun with your code instead of hating it!

Прочети цялата статия...