...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
August 26, 2012

Singleton and class instantiation in php

Question by Bojan Savic

There is a class like this in codeigniter framework ( I edited it to be more clear, full function is here http://pastebin.com/K33amh7r):

function &load_class($class, $directory = 'libraries', $prefix = 'CI_')
    {
        static $_classes = array();

        // Does the class exist?  If so, we're done...
        if (isset($_classes[$class]))
        {
            return $_classes[$class];
        }


        is_loaded($class);

        $_classes[$class] = new $name();
        return $_classes[$class];

    }

So, first time when class is loaded ( passed to this function), it will be saved to this static variable. Next time when the same class is loaded, this function checks if class exists already ( if it’s already assigned to static, cached, I’m not sure how in memory is this stored) and if it exists, it’s loaded ( NOT *instantiated* again )

As far as I can see, the only purpose is to save time or memory and not instantiate the same class twice.

My question here is: Does really instantiating a class can take up memory or consume loading time so it has to be cached like this?

Answer by ctrahey

CodeIgniter is is geared for rapid prototyping, and is really not a good example of enterprise patterns in almost any cases. This behavior is related to their design choice of the relationship the “controller” has to almost all other objects; namely that there is exactly one of almost anything (only one instance of controller, only one instance of each library, etc). This design choice is more for rapid development (justified by the developer “not having to keep track of as much” or some such…).

Basically, there is memory saved by not instantiating an object (as much memory as it takes to store the object’s instance variables) and if the object’s constructor tries to do a fair bit of work, you can save time, too.

However, the appropriateness of the single-instance imperative is clearly not universal; sometimes you really do want a new instance. When you can justify this, choose a better framework.

Answer by Starx

Its rather a simple concept, utilizing singleton-pattern it makes sure that one class is instantiated only once during an application’s execution cycle.

This sort of concept apply for libraries more. Lets see a basic example:

class Authenticate {
     public function login($username, $password) {
        ....
     }

     public function logout() {

     }
}

Now, through a execution of a page, there is hardly any case that the object of the above class, needs to be created more than once. The main thing to understand is Utilization of resources

And YES, instantiating same class over and over again will without a doubt add up in the memory, although it might be negligible like in the example I have shown, but it does affect.

Read more
August 23, 2012

I need to put script from jsFiddle to work

Question by Voyager

I have one small problem… I need to put this script http://jsfiddle.net/mctcs/ to work on my page, but i don’t know how to do it…. What to copy where, and how to make jquerry working! I don’t have pre-knowledge about jquerry and don’t know how it functions…

I need instructions like where to paste which code (head, body), and what file to make (js, html) also what values to change so it works! Can someone zipp example or something?

I would be forever gratefull!

Thanks!!

Answer by Starx

We can see the full paged version of a fiddle by adding an /show/ at the end.

Save this version of the fiddle. It contains all the scripts and resources needed for that particular fiddle to run.

Compare and meet them in your application.

Read more
August 22, 2012

Online chat with database – Fastest way?

Question by krtek

Hello I’m going to create a web based chatting program.
All chats are private, no groupboxes.

I need to keep a log of all the chats.
My idea is to push all messages to a mysql database and then check this database every half a second for incoming messages.

Is this the best way for creating the web app? The site should support 2000 users chatting simultaneously.

Are there maybe better options? I’ve seen people talking about multiple databases, text files, a combination of TCP/IP (IRC) and SQL, etc.

Answer by Starx

MySQL is capable of handling large amount concurrent request at a time, but how you manage and maintain the database is a main point.

Perfectly maintained and indexed table should show no problem. Keep the table’s structure as simple as possible. Something like

+----------------+--------------+-----------------
|    from        |     to       |   message      |
+----------------+--------------+-----------------

And, there is no perfect way to create a chat program. Depends on lots of other factors like

  • Request Type: AJAX or Comet or WebSocket
  • Application Coding: No garbage Coding, Clean OO codes following one of more Design pattens
  • Caching: Cache most of the static information as possible.
  • Data Archiving or Transaction Handling
  • Query What do you fetch together with the message (may be those things could be cached before. These things include names, avatar etc)
Read more
August 21, 2012

How to style <ul> and <li> without affecting MENU

Question by dotman14

How can I apply a different styles to the same elements at different parts of my HTML/CSS.
I have tried the following it doesn’t seem to work.

MENU

   <div class="menu">
   <ul>
         <li><a href="#"><Link 1</a></li>
         <li><a href="#"><Link 1</a></li>
         <li><a href="#"><Link 1</a></li>
  </ul>
  </div>

somewhere in the webpage

   <div class="others">
   <ul>
         <li><a href="#"><Link 1</a></li>
         <li><a href="#"><Link 1</a></li>
         <li><a href="#"><Link 1</a></li>
  </ul>
  </div>

CSS

     .menu ul,li{
         color: rgb(242,253,255);   
         list-style: none;
         text-decoration: none;
         font-size: 20px;
         font-family: chaparral pro;
         }

.others ul,li{
         color: rgb(242,253,255);   
         list-style: none;
         text-decoration: none;
         font-size: 10px;
         font-family: chaparral pro;
         }

Answer by Starx

You made a tiny mistake you generalized style of li in the following part.

.others ul,li { ..... }

The above will apply to ul inside .others and all the li through out the page. Just use

.others ul, .others li {
   /*.....*/
}
Read more

Can I call a private child constructor from a base factory method?

Question by Peter Ajtai

I’d like to implement the following using a private constructor.

The problem is that get_class() returns ParentBase; eventhough; get_called_class() returns ChildClass.

How can I have __construct() be called from the calling class context instead of the base class context?

There will be many child classes, so I only want one shared factory method, and I also want to make sure a child cannot be extended (so that it cannot be created with the new keyword).

Seems like there should be a way of making ChildClass::createObject() work with a private ChildClass constructor and a public ParentBase factory method.

<?php
class ParentBase 
{
    public static function createObject() 
    {
        echo get_class() . "<br/>";        // prints ParentBase
        echo get_called_class() . "<br/>"; // prints ChildClass
        return new static();
    }
}

class ChildClass extends ParentBase
{
    private $greeting = "bye";

    private function __construct()
    {
        $this->greeting = "hi";
    }

    public function greet()
    {
        echo $this->greeting;
    }
}

$child = ChildClass::createObject();
$child->greet();

The output from the above is:

ParentBase
ChildClass
Fatal error: Call to private ChildClass::__construct() from context 'ParentBase' 

Protected contstructor works:
http://codepad.viper-7.com/sCgJwA

Private constructor doesn’t:
http://codepad.viper-7.com/YBs7Iz

Answer by Starx

That is an expected behavior createObject(); is a function of ParentBase, So it will return ParentBase from get_class() but, it was called from ChildClass So, it will return ChildClass from get_called_class().

And about the constructor, since the constructor is assigned as private, you restrict the object creation from within the class only. By making it protected, now Parent Class can create the object of ChildClass

Probable solution would be to override, the createObject() class in the ChildClass itself.

class ChildClass extends ParentBase
{
    public static function createObject() 
    {
        echo get_class() . "<br/>";
        echo get_called_class() . "<br/>";
        return new static();
    }
}

Or, you could make the constructor protected, then you will make the constructor accessible to parent classes and restrict any sub classes of child classes making it final, thus making it accessible from parent class only.

Read more
August 19, 2012

Why is count(id) resulting 3 dimensional array?

Question by goose

Im using this direct query method in cakephp to get a count (against the norms of MVC).

$count = $this->History->query("SELECT count(id) AS x FROM ratings WHERE id='3' AND employee='28'");

But it turns out that, i need to use $count[0][0]['x'] to get the value.

Why isnt it available at $count['x']?

Answer by Starx

Simply, its because the function

$this->History->query(....);

does not return a single dimensional array. I will suggest you to create a helper function, which extracts the single dimensional array and return it.

function single_query($query) {
    $result = $this->History->query($query);
    return $result[0][0];
}

then use it

$count = $this->single_query("SELECT count(id) AS x FROM ratings WHERE id='3' AND employee='28'");
Read more

php : Show the headers received from the browser

Question by roopunk

So when a browser makes a HTTP request to a server, it is in the form some headers (get/post, cookies, host, User Agent, etc..). Is there a way I can read and display them in a php script? And yes $_GET, $_POST and $_COOKIE are there alright. I was looking for the rest of header info. eg http://pgl.yoyo.org/http/browser-headers.php Thanks.

Answer by Vito Nordloh

My favorite: http://php.net/manual/en/function.apache-request-headers.php

Fetches all HTTP request headers from the current request.

<?php
    $headers = apache_request_headers();

    foreach ($headers as $header => $value) {
        echo "$header: $value <br />n";
    }
?>

Answer by Starx

get_headers() function is what you are looking for. As quoted

get_headers — Fetches all the headers sent by the server in response
to a HTTP request

Simple example:

$url = 'http://www.example.com';   
print_r(get_headers($url));   

Outputs all the information the send by the server:

Array (

[0] => HTTP/1.1 200 OK
[1] => Date: Sat, 29 May 2004 12:28:13 GMT
[2] => Server: Apache/1.3.27 (Unix)  (Red-Hat/Linux)
[3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
[4] => ETag: "3f80f-1b6-3e1cb03b"
[5] => Accept-Ranges: bytes
[6] => Content-Length: 438
[7] => Connection: close
[8] => Content-Type: text/html )

Update

TO receive the information that is send by browsers, they can be accessed from $_SERVER super global variable. For example, the following snippet gives all the browser related information.

echo $_SERVER['HTTP_USER_AGENT'];

Similarly,

  • REQUEST_METHOD : gives the HTTP Request method such as GET, HEAD, Put, Post
  • HTTP_HOST: gives the HOST information
  • HTTP_COOKIE: gives the raw information about the Cookie header [Source]
Read more

How to create a download link for a file using PHP?

Question by Yogesh Rawal

In my job portal project, I have stored the job seekers data in MySQL Database. I have stored their uploaded resumes in the upload folder. I am able to retrieve that data of job seekers for the employers through pagination. And I want to create a download resume link of each job seeker with his data in the pagination result. How I can add the download resume link for the resume files from upload folder with each search result in the pagination?

Answer by Yogesh Rawal

Find the solution here: http://www.ssdtutorials.com/tutorials/title/download-file-with-php.html

As the file which I want to download is dynamic associated with each job seeker’s data. I used while loop for retrieving the file name from database.

    $result = mysql_query($query);
    while($row = mysql_fetch_row($result))
    {
        $filename = $row[0];
        echo "<p><a href='download.php?file=$filename'> Download Resume </a></p>";
    }

Answer by Starx

If I understood the question, this is very easy. Since you have the resume files in the upload folder. Just select the file name from the database and store on a variable lets say $filename, Like

$filename = $row['cv_filename']; // supposing $row contains the field of database

Then, use prefix the folder name in the anchor a link to that file.

$prefix = "uploads/resume";
echo "<a href='$prefix/$filename'>Download CV </a>";
Read more
August 17, 2012

Debugging in Firebug

Question by frazzle

Wonder if anyone can give some advice.

Bascially this is something I come across from time to time – I’m learning to debug using firebug and trying to track down where a style attribute is being set in a complex bunch of wordpress/fancy box files.

Bascially I’m trying to get fancybox to autosize to width of element, I know the fancybox option to enable this, but the whole box seems to be overriding with a fixed width, which i can’t find anywhere in the stylesheets.

element.style {
border-width:10px;
height:84px;
width:987px;

Now, this doesn’t have a style sheet associated on the right hand side in firebug, so I’m assuming this means its computed on the fly somewhere in the js/php ?

What I’m after is a pointer on how to track down where it’s being set, and how I can maybe use firebug to identify that if it’s being set outside the stylesheets? it’s so I can be a better debugger too 🙂 thanks for looking.

Answer by Starx

  1. First locate the element
  2. Once you do this, trigger the event, you will see the change
Read more
August 16, 2012

Unique url from primary key

Question by Prupel

I’m trying to create a URL similar to youtube’s /v=xxx in look and in behavior. In short, users will upload files and be able to access them through that URL. This URL code needs to be some form of the database’s primary key so the page can gather the data needed. I’m new to databases and this is more of a database problem than anything.

In my database I have a auto increment primary key which file data is accessed by. I want to use that number to to create the URL for files. I started looking into different hash functions, but I’m worried about collisions. I don’t want the same URL for two different files.

I also considered using uniqid() as my primary key CHAR(13), and just use that directly. But with this I’m worried about efficiency. Also looking around I can’t seem to find much about it so it’s probably a strange idea. Not to mention I would need to test for collisions when ids are generated which can be inefficient. Auto increment is a lot easier.

Is there any good solution to this? Will either of my ideas work? How can I generate a unique URL from an auto incremented primary key and avoid collisions?

I’m leaning toward my second idea, it won’t be greatly efficient, but the largest performance drawbacks are caused when things need to be added to the database (testing for collisions), which for the end user, only happens once. The other performance drawback will probably be in the actual looking of of chars instead of ints. But I’m mainly worried that it’s bad practice.

EDIT:

A simple solution would to be just to use the auto incremented value directly. Call me picky, but that looks kind of ugly.

Answer by Starx

Generating non colliding short hash will indeed be a headache. So, instead the slug format of Stackoverflow is very promising and is guaranteed to produce non duplicate url.

For example, this very same question has

http://stackoverflow.com/questions/11991785/unique-url-from-primary-key

Here, it has unique primary key and also a title to make it more SE friendly.


However as commented, they are few previously asked question, that might clear out, why? what you are trying is better left out.

  1. How to generate a unique hash for a URL?
  2. Create Tinyurl style hash

Creating short hashes increases the chances a collision a lot, so better user base64 or sha512 functions to create a secured hash.

Read more
...

Please fill the form - I will response as fast as I can!