Call to a member function format() on a non-object Symfony datetime error

When you assign time for datetime in you Entity in Symfony project, you might get this problem. The fix is simple.
If you have your entity column setup as Date or datetime like

@ORMColumn(name="date_created", type="datetime", nullable=false)

The respective setDateCreated() method expects standard datetime object.
So,

$entity->setDateCreated(new DateTime());

will solve the problem. If you want to give different time other than today’s date, then you can populate DateTime object and provide that

Unserialize giving errors at offset in php

Serialization in PHP is as easy as using serialize function. But to use the serizalized one, we need unserialize(). When you use this if you get an annoying notice of error at offset or something do this

$unserialized_value=@unserialize($serialized_value);
if ($unserialized_value)
{
    //enjoy the unserialized value here.
}

Mind you it won’t be a road blocker after all it is just a notice – but.. just cleaner is better

Country City Longitude Latitude Database setup in php

Ok, a nice Friday night here and I am working on a project that highly involves the geospatial data. For that I needed data comprising the info I needed.
Thankfully this website provided me the data as one big text file.

Then I wrote this simple snippet for porting the data to my kitchen database 😉
The script should be used only for temporary purpose and by no means on production. It doesn’t do any sanitation or what so ever the good programming.. but it does the job!
I created country_city table with the desired columns only;

CREATE TABLE `country_city` (
  `country_city_id` int(11) NOT NULL AUTO_INCREMENT,
  `country_code` char(2) NOT NULL,
  `city_name` varchar(100) DEFAULT NULL,
  `region` varchar(100) DEFAULT NULL,
  `latitude` float DEFAULT NULL,
  `longitude` float DEFAULT NULL,
  PRIMARY KEY (`country_city_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3170001 DEFAULT CHARSET=latin1

Then I run the following code to populate the data.

   <?php
   /**
    * @author Kaleb Woldearegay 
    * Code to be used "as is". Not responsible for any consequences after using the code.
    */
   const ROWS_TO_INSERT = 5000;
   $file_handle="/path/to/worldcitiespop.txt";
   $fh=fopen($file_handle, 'r');
   $query_pool=array();
   $db_handler=mysql_connect("localhost", "root", "");
   mysql_select_db("your database here");
   //assumed the database is connected at this moment..
   while(!feof($fh))
  {
      $line=fgets($fh, 1024);
      $data=explode(',', $line);
      $city=mysql_real_escape_string($data[1]);
      $query_pool[] = "(null, '{$data[0]}', '{$city}', '{$data[3]}', {$data[5]}, {$data[6]})";
      if (count($query_pool)>=ROWS_TO_INSERT)
      {
          $query = "INSERT INTO country_city VALUES " . implode(',', $query_pool);
          if (!mysql_query($query, $db_handler)) die('Error: '. mysql_error($db_handler));
          $query_pool=array();
      }
  }

That is it,
Enjoy!

symfony production path not working but works on dev environment

If you are working on the symfony and testing the changes, and you want to look at how it looks on the production env by just changing the url.. and if you are not seeing your current changes – most probably it is caching issue:
do the following being in your symfony project..

php app/console cache:clear --env=prod --no-debug

That is it

The dist file “app/config/parameters.yml.dist” does not exist. Check your dist-file config or create it.

Are you upgrading symfony to 2.3. Bum! This will be the problem you would face after upgrading the composer.json file and trying to do 

composer.phar install 

the solution is simple. Just copy the existing parameters.yml file from app/config/ folder to new file called parameters.yml.dist and rerun the command

Single id is not allowed on composite primary key in entity Doctrine error

You might get the above error on PHP Doctrine

if you got the above error, then it means you have two or more ids as primary in your object representing the table.

Example:

class Member
   /** @id 
    * @Column(type="integer") 
    * @GeneratedValue(strategy="AUTO")
    */
   private $id;
   /** @id @Column(type="string") */
   private $key;
...

The above declaration would create the above error and taking out the generatedValue part can resolve the issue.

See the solution to common error of new entity was found though relation while using doctrine

How to automate http authentication url from php

if you have to download a file from a web address that would trigger a username and password window (http authentication), then here is the trick

$downloaded_content = file_get_contents("http[s]://yourusername:yourpassword@thefiledownloadurl");
file_put_contents('/tmp/tempholder.csv', $downloaded_content);

The line of interest would be the first one with file_get_contents.
Once you get the content, you can perform a lot of things, either use the content as it is, or copy it to file using file object or just simply transfer the content to other file as the example depicts..

mod_rewrite not working on mac. Enabling .htaccess problem on mac

As a PHPer you would know what the mod_rewrite is and what the .htaccess file is right? if not a bit of googling would shower with a bunch of tutorials.
Now to the point:)
Being on mac do the following to enable mod_rewrite
1. Check if the module is loaded.
Navigate to apache2 folder

cd /etc/apache2

and open the conf file

sudo vi httpd.conf

Now, search for rewrite and you will and to something like this one

LoadModule rewrite_module libexec/apache2/mod_rewrite.so

if it is commented out, that is if there is a #infront of it, uncomment it and exit
2. Being in the current file, search for AllowOverride and replace the “None” by “All”

3. Got to the directory /etc/apache2/users and open the conf file of your username. Like if your username is gullele, there would be file gullele.conf. Bing inside the file, search for AllowOverride and give it the value of “All”

now restart your server

sudo apachectl restart

Happy rewriting :)

Enabling PHP in Mac Mountain Lion

I have been using snow leopard and recently I got a new mac with mountain Lion. As a PHPer the first thing I was doing was to install php+mysql and I have found it much easier

here is how to enable apache for PHP:

1. go to terminal, click the launch icon from dock and you will find it in the utilities, and do
apachectrl start – you need a sudo access for this
2. Go to system preferences -> internet and wireless -> sharing and check web sharing
3. Now, go to http://localhost and verify the it works is there.
4. Then being on your editor, go to /etc/apache2 and open httpd.conf file. Then look for php5_module and uncomment that line.
5. You are done. For testing, go to /Library/Webserver/Documents/ and add a php file named phpinfo.php with content of phpinfo(); and access it from http://localhost/phpinfo.php

Happy PHP