Register Doctrine2 type mapping with Symfony2

Well, few of us may have encountered such error while using Doctrine like “Unknown database type enum requested, Doctrine\DBAL\Platforms\MySqlPlatform may not support it.” or in my case I was trying to use “enum” type with doctrine.

So, here is the app/config.yml hack at mapping_types:

# Doctrine Configuration
doctrine:
    dbal:
        driver:   %database_driver%
        host:     %database_host%
        port:     %database_port%
        dbname:   %database_name%
        user:     %database_user%
        password: %database_password%
        charset:  UTF8

        mapping_types:
          enum: string
          set: string
          varbinary: string
          tinyblob: text
    orm:
        auto_generate_proxy_classes: %kernel.debug%
        auto_mapping: true
Advertisements

Setting your PHP development environment in Ubuntu

Instead of installing each item separately we will go with installing LAMP server in a package in Ubuntu that is fairly simple along with a single terminal command:

sudo apt-get install lamp-server^

The apt-get command is a powerful command-line tool used to work with Ubuntu’s Advanced Packaging Tool (APT) performing such functions as installation of new software packages, upgrade of existing software packages, updating of the package list index, and even upgrading the entire Ubuntu system.

sudo used to invoke the current user with the power of super user and a caret ‘^’ symbol placed after package name to indicate performing as tasks together.

The LAMP package will start installing immediately with above command including latest PHP5, Apache 2, MySQL and PHP5-MySQL. By default apache2 and MySQL installed as service and your document root will be at /var/www/

An index.html file shall be there.

Both Apache and MySQL should be running. However, you may start apache by using service start command as

sudo service apache2 start

and stop apache by using:

sudo service apache2 stop

Checking the LAMP installation:

Point your browser to http://localhost/ you will see the default apache2 landing page which means your webserver apache2 is running. Still you can check those service statuses as below:

sudo service apache2 status

you will be shown

Apache is running. Process #

Again to check MySQL status, simple run the command

sudo service mysql status

you will be shown

mysql start/running. Process #

to check the PHP installation simple create a file named test.php, in /var/www/ with the below line:

<?php phpinfo(); ?>

Now point your browser with http://localhost/test.php and you will see the installed PHP and components configuration details.

Installing PhpMyAdmin:

To maintain MySQL database functionality using web based interface we may use phpMyAdmin.

sudo apt-get install phpmyadmin

phpMyAdmin will be installed with the above command and during installation you will receive a blue window asking which server you want to use i.e. apache2, lighttpd ;  choose apache2 and click ok to continue with the installation. After installation point your browser with http://localhost/phpmyadmin/ and you will be viewing phpMyAdmin landing page.

If you receive 404 error at http://localhost/phpmyadmin/ then you need to setup phpMyAdmin under apache manually by modifying /etc/apache2/apache2.conf using gedit

sudo gedit  /etc/apache2/apache2.conf

gedit will open the file in graphical mode and add the below line at bottom inside apache2.conf

Include /etc/phpmyadmin/apache.conf

Now restart apache server to make the changes effective.

sudo service apache2 restart

Now refresh your browser and you will have phpMyAdmin login screen.

BASIS SoftEXPO 2012 Tech session: Build Social Apps for Facebook

The below application created to describe simple Facebook social plugins usage and how to develop a Facebook app from scratch.

The demo Facebook application : BookStall

The Entire Facebook application source code can be downloaded from here:

Virtual bookstall project source codes

screen-casts will be added soon 🙂 [N.B: 44 minutes screen-casts are too heavy to upload, skipped this]

This above session has been presented at BASIS SoftEXPO 2012

PhpXperts Seminar 2011 – follow up

17th December 2011, on tech premises at the heart of Dhaka, the largest tech seminar took place once again featuring latest web trends and interesting PHP sessions brought by the experts from the industry. In this 5th annual program of phpXperts, more than 500 developers, open source enthusiasts, journalists, students, geeks joined the daylong event to inhabit the tech gathering which finally became huge success and significant in the local PHP community.

This long awaited annual program included with a new addition of short sessions of 6 minutes each along with regular sessions with speakers and the sponsors presented their companies or projects within the event frame. The pretty item in the seminar was the quiz session after each two speaking and winners were awarded with many exciting gadgets.

Basically openness & friendliness of phpXperts community became the icon of tech community of the country, more auspicious developers have been stimulated from the phpXperts. This enormous tech group feeds heavy input to local web industry and the web generation of Bangladesh.

Hasin Hayder, the man behind the scene, doing the hard work as founder-moderator of the group and the mentor to local PHP community.

Seminar references are as below:

.

Sessions with Speakers

Lets have some fun with – Twilio & OpenTok APIMizanur Rahman

Get Excited! Enterprise Search Solutions at your FingerTipsMurshed Ahmmad Khan

Dependency Injection, Reinventing how you manage PHP classesRifat Nabi

Setting up Amazon EC2 Servers: Make Your Server Elastic!Tahsin Hasan

Continuous feature integration in large projectsNHM Tanveer Hasan Khan & Nafi ul karim

MongoDB, a document store that won’t let you down!Nurul Ferdous

Getting Up and running with Zend FrameworkMd. Shoriful Islam Ronju & Saidur Rahman Bijon

A Brief Intro to the Symfony Application Framework v2.xLoban Amaan Rahman

Screencast: http://www.youtube.com/watch?v=ENR3qXdNOXY

Taking Advantage of Client Side / JavaScript Templates in Rich Internet Applications. – M. Mahbubur Rahman

Hybrid authentication and talking to social networksRayhan Chowdhury

Supervisor, Gearman and PHP – Job management with sanity!Abu Ashraf Masnun

Mystery of cryptography, ciphers and the dark side of the moonHasin Hayder & M A Hossain Tonu

.

6 minutes of Fame

Smelling Your CodeRaju Mazumder

WordPress plugin / theme development best practicesTareq Hasan

Flying on the cloudImran Hossain Shaon

Rapid facebook application development using LightBulb – Md. Alamgir Hossain Rinku

ZCE – Inside OutShehzad Noor Taus

RESTful Web ServicesMd. Eftakhairul Islam Rain

Download all the presentation slides:

http://seminar2011.phpxperts.net/phpXperts%20Slide%202011.zip

Seminar booklet:

Cover Design of the booklet of phpXperts

Photo Albums:

http://www.facebook.com/media/set/?set=a.10151054439780608.776901.584190607&type=1

http://www.facebook.com/media/set/?set=a.2830854448579.148339.1175663829&type=3

Seminar follow up in Bengali:

http://www.techtunes.com.bd/reports/tune-id/102066/

Cheers 🙂

Multiple Database from application.ini in Zend Framework

place something like in your application.ini

[production]

resources.multidb.db1.adapter = "pdo_mysql"
resources.multidb.db1.host = "localhost"
resources.multidb.db1.username = "webuser"
resources.multidb.db1.password = "XXXX"
resources.multidb.db1.dbname = "db1"


resources.multidb.db2.adapter = "pdo_pgsql"
resources.multidb.db2.host = "example.com"
resources.multidb.db2.username = "dba"
resources.multidb.db2.password = "notthatpublic"
resources.multidb.db2.dbname = "db2"
resources.multidb.db2.default = true

you should declare the default database as we did in
resources.multidb.db2.default = true

if you want to retrieve a specific database adapter may use from followings:


$resource = $bootstrap->getPluginResource('multidb');

$db1 = $resource->getDb('db1');

$db2 = $resource->getDb('db2');

$defaultDb = $resource->getDb();
//or
$defaultDb = $resource->getDefaultDb();

getDb() returns an instance of a class that extends Zend_Db_Adapter_Abstract.
If you have not set a default database, an exception will be thrown when this method is called without specifying a parameter.

code says it all 🙂

 

Bootstrap-ing in Zend Framework

.

Bootstrap.php inside your application directory runs before your application loads in order to process auto loading of resources. resource auto loading can be performed in two ways using either Bootstrap.php or application.ini for an application.

Bootstrap methods used as initialize-r should be of protected and begin with _init.

As an example, you want to initialize language translation resource, create a method like _initTranslation() as below:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
      protected function _initTranslation(){
      //translation enabling codes here
      }
}

bootstrap methods are named according to functionality i.e. _initLayout(), _initViewHelpers(), _initRoutes() etc.

here are two examples of bootstrap methods:

jQuery, jQuery ui/css enabler

/**
 * enable jquery, jqueryui, css
 **/
protected function _initJquery() {
  $this->bootstrap('view');
  $view = $this->getResource('view');

  //add jquery view helper path
  $view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");
  //jquery lib includes here
  $view->jQuery()->enable()
       ->setVersion('1.5')
       ->setUiVersion('1.8')
       ->addStylesheet('https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/ui-lightness/jquery-ui.css')
       ->uiEnable();
}

in the above code we just enabled to make available jQuery, ui to our application.

doc type, header

/**
 * declare header, doc type etc.
 **/
protected function _initDoctype() {
   $this->bootstrap('view');
   $view = $this->getResource('view');

   //doc type
   $view->doctype('XHTML1_STRICT');
   $view->headMeta()->appendHttpEquiv('Content-type', 'text/html;charset=utf-8')
        ->appendName('description', 'test description');
   }

in the above method we declared doc type, charset etc. for our html documents belongs to the application.
.

Using Multiple Layouts in Zend Framework

Followed by my earlier post >>

Besides using default layout you can use multiple layouts or can switch between layouts. All you need to do is just pick the layout object and set the desired layout name.

Here is a scenario:

Say you have 2 layouts at application/layouts/scripts/ i.e. layout.phtml and layout1.phtml

As layout.phtml is your default layout and you need to use layout1 in some cases. To do that we need to pick the layout object as mentioned earlier, there are several ways.

Access a layout object:

At view scripts:

<?php $layout = $this->layout(); ?>

At action controller:

$layout = $this->_helper->layout();

Static method elsewhere:

$layout = Zend_Layout::getMvcInstance();

At bootstrap:

$layout = $bootstrap->getResource('Layout');

Set the desired layout (the layout will work within defined scope):

$layout->setLayout('layout1');

i.e. If you set the layout at any action controller then the layout will be viewed for that particular action.

For more reading

http://framework.zend.com/manual/en/learning.layout.usage.html

Enabling Layout in Zend Framework

See Category:Go images for sourcecode and usag...
Image via Wikipedia

To maintain a consistent look and feel through out your website, Zend_Layout provides layout facility by which you can create single or multiple document structures as like as templates.

Enabling Zend_Layout means informing bootstrap to use Layout resource. You can enable layout with the help of zf cli tools from terminal as:


$ zf enable layout

Layout has been enabled, and a default layout created at application/layouts/scripts/layout.phtml. A layout entry has been added to the application config file.

With the above command you will have following things ready:

–       application/configs/application.ini is updated; contains following line at your production section


resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"

–       A layout file created at /application/layouts/scripts/layout.phtml

Also you need to initialize the View resource; add the following line to your have application/configs/application.ini


; Add to [production] section:

resources.view[] =

Now to run view resource we will add just a little code at bootstrap:


class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {

protected function _initView(){

$this->bootstrap('view');

$view = $this->getResource('view');

$view->doctype('XHTML1_STRICT'); //can set the doc type here

}

}

Now  Zend_Layout is ready to go; may modify the layout or add some styles. Just don’t forget to echo your content i.e. $this->layout()->content  at your layout body to display your content or view html segments:


<!-- application/layouts/scripts/layout.phtml -->

<?php echo $this->doctype() ?>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>my title</title>

</head>

<body>

<?php echo $this->layout()->content ?>

</body>

</html>

It’s a go!

if you need to use multiple layouts, you may read my next post on multiple layout usage

Using jQuery and jQuery ui with Zend Framework

talkin' jquery ui
Image by "Cowboy" Ben Alman via Flickr

.

For those jQuery fanatics like me wants to jQuery enabled in their Zend framework application, zf provides view and form helpers through it ‘extras’ library, also it is handy to enable.

At Bootstrap class add the following initialization method like below:

/**
* init jquery view helper, enable jquery, jqueryui, jquery ui css
*/

protected function _initJquery() {

$this->bootstrap('view');
$view = $this->getResource('view'); //get the view object

//add the jquery view helper path into your project
$view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");

//jquery lib includes here (default loads from google CDN)
$view->jQuery()->enable()//enable jquery ; ->setCdnSsl(true) if need to load from ssl location
     ->setVersion('1.5')//jQuery version, automatically 1.5 = 1.5.latest
     ->setUiVersion('1.8')//jQuery UI version, automatically 1.8 = 1.8.latest
     ->addStylesheet('https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/ui-lightness/jquery-ui.css')//add the css
     ->uiEnable();//enable ui

}

At the <head> section of your document or at layout.html, to enable jQuery at your each pages just echo like below:

<?php

echo $this->jQuery();

?>

So you will have jQuery and jQuery ui files added into your document section like as always:

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/ui-lightness/jquery-ui.css" type="text/css" media="screen" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

Cheers!

N.B: in order to use ZendX library under extras/library/ZendX, the ZendX directory path should be in your php include_path or alternatively can SymLink the ZendX directory under your /application/library/

.

Setting up your development with Zend Framework

.

In general, Zend Framework is an object oriented web application framework for PHP 5. Zend Framework is often called a ‘component library’, because it has many loosely coupled components that you can use more or less independently. It also provides advanced Model-View-Controller implementation.

In order to setup the development environment with Zend framework we will go through the below procedures:

1. Download and Install

Download the latest version of Zend Framework and extract the contents into your desired location or can have a checkout copy from the Subversion repository.

Some extensions may be required such as GD, iconv etc. (Zend Framework will notify you if any required while your application runs, so don’t worry about that now). If you are much interested about those extensions required can read more here

2. Creating your project using zf Command Line Tool

Before creating your project you need to know the use of zf command line tool. Here we go

In your Zend Framework installation is a bin/ subdirectory

for *nix =  zf.sh and for Windows = zf.bat . Track the absolute path to that script.

On Unix-like systems, you may want to use your shell’s alias functionality:

$ alias zf =path/to/ZendFramework/bin/zf.sh

If you have problems setting up the zf command-line tool, please refer to the manual.

Now from the terminal or command prompt, execute following command

$ zf create project projectname projectpath

This will create your basic project director structure i.e. directory for controllers, models, views etc.

3. Add Zend Framework to your include_path

Now either choose a) or b) to make available the zf components to your project. I like b)

a)     Add Zend Framework installation path to your php include_path

b)    Symlinking path/to/ZendFramework/library/Zend inside your path/to/projectname/library/ with this command

$ ln -s path/to/ZendFramework/library/Zend path/to/projectname/library/

If you are planning to use jQuery later you may Symlink the ZendX directory found under extras/library inside your project library as:

$ ln -s path/to/ZendFramework/extras/library/ZendX path/to/projectname/library/

So you will have alias to above Zend directories inside your project library sub directory. All you are doing is just making Zend Framework available to your project. You may follow identical practice for multiple zf projects.

4. Bootstrap-ing

Bootstrap class defines what resources and components to initialize. Zend framework runs the Bootstrap.php(can be found just under each application dir) file before loading any modules or applications. So we can put all sort of initialization tasks there.

As an example, we put doc type initializer inside the class as below:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
protected function _initDoctype() {
$this->bootstrap('view');
$view = $this->getResource('view');
//doc type
$view->doctype('XHTML1_STRICT'); // doc type to xhtml strict
$view->headMeta()->appendHttpEquiv('Content-type', 'text/html;charset=utf-8') //utf-8 enabled
->appendName('description', 'my zf project');
}
}

5. Configuration

The default configuration file can be found under /application/configs/application.ini

It looks like below:

; application/configs/application.ini
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
[staging : production]
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1

You can update the file as per your requirements. As for an example, lets add database connection credential at [production] section, so the zf connects the database automatically using the config provided as below

;DB connection credentials
resources.db.adapter = "PDO_MYSQL" //pdo adpter for mysql
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = "root"
resources.db.params.dbname = "test_database"

So you will have your database connected with your zf project.

6. Creating action controllers, views as well

Run the following command using zf cli tool to create controller each time:

$ zf create controller name

Now you will have a controller class created inside your controller directory and a view subdirectory (same name) created with default index view file named index.phtml inside your views directory.

To create action method under that controller class simple run the command:

$zf create action name controllername

By this you will have the view file with the same name created automatically for that action method too.

You may follow up the changes appearing each time at that controller class by opening it.

Up to now you suppose to be able to browse your project by visiting url like http://localhost/projectname/public/

7. Creating views (optional)

Run the following command using zf cli tool to create view file explicitly for a controller/action each time:

$ zf create view controllername actionname

8. Creating virtual host (optional)

Assuming you are using Apache web server, at your working httpd.conf define a vhost by adding the below snippet (replace myzfproject with your project name, also the path):

<VirtualHost *:80>
ServerName www.myzfproject.com
DocumentRoot /path/to/ myzfproject /public
SetEnv APPLICATION_ENV "development"
<Directory /path/to/ myzfproject /public>
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>

Using SetEnv APPLICATION_ENV “development” line you are setting the environment variable for zf application, resulting the zf will pick configurations from [development] section from application.ini. Drop this line for having “production” config by default.

Add an entry at the end of your hosts file regarding the value in ServerName :

127.0.0.1 www.myzfproject.com

Location of hosts file:

On *nix: /etc/hosts On Windows: C:\WINDOWS\system32\drivers\etc\hosts

Restart your web server and you are likely to drive.

Visit http://framework.zend.com for more information

Both Zend Developer Zone and the Wiki have links to ZF tutorials and articles. Consider subscribing to the fw-general mailing list but especially the SVN commit list