Using Javascript and PHP to Upload Files

Hi,

As many of you know the HTML file input element is very very primitive. It accepts very little styling, etc. My problem was I had to upload files to a server, but not refreshing the page. I figured this could be possible with AJAX, but the problem was simpler, using IFrames. OK, this is not recommended by some people, but for this purpose it is just good.

The script uses unobtrusive Javascript coding, which means it works even if Javascript is disabled. My javascript file that does all the work is just 1,135 kb unpacked with comments. For server-side I used PHP, but this is not required.

Inside the zip file is a direcotry called Upload for which writing permissions must be set. It works with Firefox 1.5+, Internet Explorer 5+ (not on mac), Opera 9+, Safari 2+

You can download it here:

My Ajax Upload

PHP: Convert Array Notation to Object Notation

Update:

Here is a hardcore one-liner from a forum posting (thanks man). It seems I wasted my time for nothing…again…


function array2obj($data) {
return is_array($data) ? (object) array_map(__FUNCTION__,$data) : $data;
}

$data = array();
$data['db']['def']['host'] = 'localhost';
$data['db']['def']['username'] = 'username';
$data['db']['def']['pw'] = 'password';
var_dump(array2obj($data));

And still if you want a more elegant version of it read on. This code above takes up 72 in memory, mine 2536. Yeah sweet…

I spent a whole day figuring out how to do this. Converting and array to an object. Object notation to be more precise.

Here’s an example:

I want this:


$data['db']['default']['host'] = 'localhost';

$data['db']['default']['username'] = 'root';

Converted to this


$data->db->default->host;

$data->db->default->username;

Then I found stdClass(). And with a little ‘recursive class’ I finally coded the stuff. Here it is:


class objArray

{

function __construct($data=null, &$node=null)

{

foreach ( $data as $key => $value )

{

if ( is_array($value) )

{

if (! $node )

{

$node =& $this;

}

$node->$key = new stdClass();

self::__construct($value,$node->$key);

}

else

{

if (! $node )

{

$node =& $this;

}

$node->$key = $value;

}

}

}

}

$data = array();

$data['node1'] ['subnode1'] = 'node1-subnode1';

$data['node1'] ['subnode2'] = 'node1-subnode2';

$data['node2'] ['subnode1'] = 'node2-subnode1';

$data['node2'] ['subnode2'] = 'node2-subnode2';

$obj = new objArray($data);

var_dump($obj);

Tools: CodeIgniter

CodeIgniter is a framework for PHP. It is best for small to mid scale web application projects.

Advantages:

  • fast
  • small
  • supports caching
  • built-in helper classes

Disadvantages:

  • folder structure is confusing
  • doesn’t support ‘true’ modularity
  • workaround to create partial views

Verdict: You should try it out and use it for small projects, but for larger projects I don’t recommend it.

PHP Inheriting From Multiple Objects

Good title eh? Well in PHP it’s known that you can extend only one class like this:


class A {

function __construct() {

echo ' class A |';

}

}

class B extends A {

function __construct() {

parent::__construct();

echo ' class B | ';

}

}

Of course you can create an additional class C which extends class B and you also get the properties and methods of class A.

BUT this means you stack up all of your classes extending each other, which makes reusability a nightmare.

What you can do about this is involving a PHP hidden gem called dynamic variable creation. For ex. can you figure out what the code below is doing?


$tmp = 'good';

$$tmp = 'stuff';

Do you see the double $$ ? It means that from the value of $tmp a new variable is created. It’s logical, because the value of $tmp is good so $$tmp means $good. And $$tmp = ’stuff’; will add the value ’stuff’ to $good.

Now we can use this method in object inheritance. The idea is to create a super object which are instantiating other objects. And by extending this new super object we get something like this:

This can be done with dynamic variable creation. Each object (object 1, object 2, object 3) will be instantiated in the super object (representing the blue dashed lines on the picture). Each object will become a dynamically created variable with the same name as the object itself (except it’s lowercase in our example). The cool trick is the super object can conditionally create other objects. The code below demonstrates that:


class SuperObject{
function __construct($what)
{
//class always instantiated
$var = 'Object1';
$low_var = strtolower($var);

$this->$low_var = new $var;
//-------------------------

//optional classes instantiated
foreach($what as $var)
{
$low_var = strtolower($var);
$this->$low_var = new $var;
}
}
}
class Object1 {
function __construct(){
echo ' Object 1 | ';
}
function test(){
echo 'test function from Object 1';
}
}
class Object2 {
function __construct(){
echo ' optional Object 2 | ';
}
}
class OurObject extends SuperObject{
function __construct(){
$what[0] = 'Object 2';

parent::__construct($what);

$this->object1->test();
}
}

$tmp = new OurObject();

As you can see by extending OurObject with SuperObject we get to the other object’s method and properties. If you examine the SuperObject then you’ll see that the Object2 is instantiated conditionally.

This approach can be useful with modular PHP applications where we can plug-in a module to our super object and use it’s methods and properties. Or we extend our module with the super object and tell it which core objects to load.

BlogRush

I heard about this blog widget somewhere on the Internet. I thought i give it a try. It suppose to bring a huge amount of traffic to your site. You can see the widget on the right sidebar. If you want to try it out for yourself you can sign up here

And don’t forget to check out my other posts.

Effective Time Management Theory

Hello, I like to write about my own time management theory that I apply on projects and it works very well. OK, every project generally is the same. You have tasks that you have to finish in order to finish the whole project, but how to complete these tasks to deliver the whole project in record time.

I don’t consider my theory ground breaking, I kept it to me until now. I want to hear about your opinion. Picture this:

We have tasks that are different. We got important tasks, not so important tasks, tasks that are takes time to finish and tasks that are not. So we can group these tasks in 4 categories like on this picture:

Time management Pic1

The black circles are tasks. How can we optimize these tasks? We some how must modify the tasks or the whole project to bring all the tasks in the 2 part of the picture, so they become important and takes less time to finish. The goal is to optimize the whole project, by doing these tasks (2 part on the picture) because it can be done quickly.

We call the bottom part of the picture, the 3th and 4th part, control tasks, because they’re not so important, but regularly checking on them, we could find control tasks that by finishing it makes the other important and time consuming tasks move to the 2 part of the picture, becoming less time consuming, but important.

I call this ‘task relation’ keys. Generally all task can be keys, but usually control tasks are more likely to become one, because of the regularly checking. It is a good practice to check control tasks on each finished important - less time consuming task. The final diagram looks like this:

Time management Pic2

The idea is to find keys that can optimize the project reducing the time and increasing the importance of that task(s). Hope you enjoyed this article,  I want to hear your opinion, so if you can please comment on this.

Basics of Framework Design in PHP

If you consider developing a framework you should begin with the logic of framework design. This article will show you the concepts of framework building. We will be discussing framework logic with MVC pattern in mind.

First we have to understand what the framework should do. Frameworks help developers minimizing repetitive code that is easily manageable and reusable. If we break up a PHP web application (generally websites) we find that some areas of the code could be isolated from the rest of the logic and reused in other projects as well. We like to call these codes modules.

Now we have to understand the code flow. What happens when a user visits our website, makes a request. For example if a user requests to see the ‘work’ section on our website (www.primalskill.com/en/work) the application figures out what section of the website is required, gets the data from a database, formatting it so it will be nice and sends it to the user.

By figuring out which section is requested is generally done looking at the URL. In the example above you can see in the URL there is the word ‘work’. This means the user wants to see the websites ‘work’ page. In framework thinking this could be a module. But that’s a little bit more complicated.

In a module based framework a request looks something like this:

Framework Flowchart

The front controllers job is to load the general classes, the master configuration files and based on the request figure out which module to load.

The module job is to get the requested data from a database, file, etc. format the data and send it back to the user.

In the front controller layer we can implement security and URL routing filter classes. We can load a database abstraction class and pass it to the module.

It’s a good practice to keep your files strictly organized in folders with access rights and so on. I will present here a general project folder structure:

Framework Structure

Here you can see the general structure of a project. The ‘root - libraries’ folder holds all the common classes that a modules may use, like database abstraction class, error handler class, etc. The ‘master’ folder contains a main front controller. This file loads general modules, master configuration and resolves which module to load. Each module has separate controllers, models, views and configuration specific to that module.

It’s a best practice to turn the error reporting off when you put the application online, but also know when an error is occured, that’s why is a good advice to make a logs folder and put the exception handler generated files in here.

Of course there are lot’s and lot’s of other file structuring frameworks, this is just one of that many. I hope you enjoyed reading this article and check back soon for new ones.

Syntax Highlight for Wordpress

This blog uses Wordpress as the blog engine. And I thought that I will write some code in my posts, but wanted to make it prettier, with syntax highlighting. I checked out some of the color coding plugins for Wordpress and best plugin out there is what I’m using right now, called SyntaxHighlighter. It uses Google Syntax Highlighting engine and it’s great.

It supports lot’s of programming languages, like PHP, Javascript, CSS, HTML, XHTML,etc.

Here are some code highlighting examples:

PHP:


function foo() {

echo 'Hello World';

}

Javascript:


function foo() {

alert('Hello World');

}

You should check this plugin it’s worth it.

Creating a Custom Framework

We don’t really like to use 3rd party frameworks. That’s a fact. The reasons are many, we can’t oversee the whole framework’s code and eventual bugs, security holes. 3rd party frameworks are made for a large audience of developers, therefore they’re are very generally coded.

For ex. we mostly use MySQL for database, but frameworks offer abstraction code for lot’s of varieties of other databases which generally takes up space and server memory, because on each request they have to check which database abstraction class to use (of course there are other loading methods as well).

The logic behind frameworks are not very complex. By far the best way to develop a framework is by creating classes and let them evolve over time. The idea is to organize these classes very carefully, and apply the same programming style/principles each time when we extend our classes.

What kind of classes to create and let evolve?

Well the answer to this question varies. You should create classes to apply as many projects as possible, like database handler classes, security and administration classes, etc.

Extend these classes over time, kill bugs and security holes in them, add new features/functionality, etc.

How to organize these classes to use them in a project?

We generally use the same programming principles and techniques and patterns for every project. Like the KISS PrincipleMVC pattern . This pattern is best for mid to large scale projects and excluded from small scale projects, because of the KISS principle :-) You can search for lot’s of useful tutorials on these programming techniques.

As of file organization we organize each class in separate files and naming them accordingly. We keep our controller, model and view classes in different folders. The Symfony framework’s documentation is a very good start in organizing an MVC project.  Adding to this file organization, we keep separated the administration part from the front-end application. And keep different classes for them. This is a security measure.

That’s it for now, in future posts I will write about more on MVC pattern and how to implement that. I hope you enjoyed reading this article.

Tools at Primal Skill

If you’re a starting web developer and you don’t know what tools to use let me reveal what tools we are using here at Primal Skill. First of all here are designers, developers, seo specialists who use different tools each. I will list a few of them here and I will write about each tool in detail on the following posts.

Developers:

We are programming mainly in PHP on Apache server and using MySQL as a database engine. The IDE we’re using is Aptana (which I consider the best opensource code editor, but still a little buggy) and that’s about it. All we need is this IDE :-)

Oh, and some PHP frameworks like CodeIgniter and Symphony.

Front-end developers, designers:

The same IDE. Also our main testing browser is Firefox, we don’t really like IE. We use quite a lot of Firefox plugins like Firebug, Greasemonkey, YSlow and last but not least Web Developer Toolbar. These plugins are very very useful in developing and debugging client side code. Adobe AIR for ‘browserless’ web applications, but this is integrated in Aptana. Our most used Javascript frameworks are jQuery and YUI .

We like to create project time sheets and price sheets mostly in Google Docs. These spreadsheets are for our clients. For big projects we use activeCollab project management tool.

You should try out these tools, to make you life easier. And check back for later posts where I’m going to write about these tools in detail.

Enjoy.