Showing posts with label ZF2. Show all posts
Showing posts with label ZF2. Show all posts

Friday 22 November 2019

How to setup different configs in server (development, production)?

How to implement different configs for development, production?

Question: How to implement different configs for development, production etc?
  1. Added following line in .htacess (Location: /public/.htaccess)
    SetEnv APPLICATION_ENV development
    This is for development.
  2. Open application.config.php in /config/application.config.php
  3. Get the current environment.
    $applicationEnv = getenv('APPLICATION_ENV');

    Dynamic the file like below:
            'config_glob_paths' => array(         
                "config/autoload/{,*.}{$applicationEnv}.php"
            )
  4. Create the config files like below in /config/autoload
    development.php
    production.php
    
  5. Below are the sample of config file.
    return array(
        'db' => array(
            'driver' => 'Pdo',
            'dsn' => 'mysql:dbname=DBNAME;host=HOST',
            'username' => 'DB_USERNAME',
            'password' => 'DB_PASSWORD'
        )
    );
    Please update the database credentials.

Sunday 4 August 2019

How to post raw data using CURL in Zend Framework 2

How to post raw data using CURL in Zend Framework 2

Question: How to post raw data using Zend?
        $client = new Client('http://example.com/ajax/get-feedback-status', array(
            'maxredirects' => 0,
            'timeout' => 30
        ));

        // Performing a POST request
        $client->setMethod('POST');
        //Set data
        $client->setParameterGet(array(
            'first_name' => 'Web',
            'middle_name' => 'Technology',
            'last_name' => 'Experts',
            'category' => 'notes',
        ));
        $response = $client->send();
        if ($response->isSuccess()) {
            // the POST was successful
            echo $response->getBody();
        } else {
            echo 'Request is failed';
        }





Question: Can we post Multi dimensional array in Zend?
Yes, See example below.
        $client = new Client('http://example.com/ajax/get-feedback-status', array(
            'maxredirects' => 0,
            'timeout' => 30
        ));

        // Performing a POST request
        $client->setMethod('POST');
        //Set data
        $client->setParameterGet(array(
            'first_name' => 'Web',
            'middle_name' => 'Technology',
            'last_name' => 'Experts',            
            'post-ids' => array(10, 20, 30)
        ));



Question: How to add Cookie in httpClient Object?
        $client = new Client('http://example.com/ajax/get-feedback-status', array(
            'maxredirects' => 0,
            'timeout' => 30
        ));
        $cookieString = \Zend\Http\Header\SetCookie::fromString('Set-Cookie: flavor=chocolate%20chips');
        $client->addCookie($cookieString);



Question: How to change the HTTPS transport layer in httpClient Request?
        $config = array(
            'adapter' => 'Zend\Http\Client\Adapter\Socket',
            'ssltransport' => 'tls'
        );

        $client = new Client('http://example.com/ajax/get-feedback-status', $config);
        $cookieString = \Zend\Http\Header\SetCookie::fromString('Set-Cookie: flavor=chocolate%20chips');
        $client->addCookie($cookieString);



Question: How to call curl From proxy server?
        $config = array(
            'adapter'    => 'Zend\Http\Client\Adapter\Proxy',
            'proxy_host' => 'ADD HERE POST',
            'proxy_port' => 8000,
            'proxy_user' => 'USERNAME',
            'proxy_pass' => 'PASSWORD'
        );

        $client = new Client('http://example.com/ajax/get-feedback-status', $config);
        
        $client->setMethod('GET');        
        
        $response = $client->send();
        
    if ($response->isSuccess()) {
            // the POST was successful
            echo $response->getBody();
        } else {
            echo 'Request is failed';
        }
        


Thursday 10 January 2019

PHP namespace example - Tutorial

PHP namespace example - Tutorial

Question: What is namespace in PHP?
namespace is reserve keywords which is used to encapsulating the class, method, data member variables and static methods.


Question: Benefits of namespace in PHP?
  1. Encapsulate the data which fixed collisions between code you create, and internal PHP classes/functions/constants.
  2. Ability to alias which improved the readability of source code.



Question: Which PHP Version support namespaces?
PHP5.3



Question: How namespaces are defined?
namespaces are defined with keyword namespace
For Example:
namespace math



Question: Example - Simple class without namespace (OR Global namespace)?
File: /myproject/simple-file.php
class mathSimple {

    function add($a, $b) {
        return $a + $b;
    }

}

File: /myproject/run-example.php
include "simple-file.php";

$obj1 = new mathSimple(); //calling for Global Namespace
echo $obj1->add(10,20);//30

When we execute run-example.php file, it will return 30


Question: Example - Simple class with namespace?
File: /myproject/namespace-file.php
namespace math;

class mathSimple {

    function add() {        
        return array_sum(func_get_args()) ;
    }

}

File: /myproject/run-example.php
namespace math;
include "simple-file.php";
include "namespace-file.php";


$obj1 = new \mathSimple(); //calling for Global Namespace
echo $obj1->add(10,20,30);

echo "\n";
$obj2 = new mathSimple(); //calling for namespace math
echo $obj2->add(10,20,30);
Question: How to import namespaces?
use Zend\View\Model\ViewModel;



Question: How to use alias namespaces for import namespace?
use Zend\View\Model\ViewModel as ZendViewModel;



Question: Can we override the php in-built using namespace?
Yes, We can do. File: /myproject/namespace-file2.php
namespace math;

class mathSimple {

    function add() {        
        return array_sum(func_get_args()) ;
    }

}
function strlen($string){
    return 'in built functi';
}


File: /myproject/run-example2.php
namespace math;
include "namespace-file2.php";

echo strlen('string'); //calling namespace function
echo \strlen('strlen'); //calling inbuilt function


Tuesday 8 January 2019

Zend Framework modules questions and answers

Zend Framework modules questions and answers

Question: What are the basic steps for create new module?
Suppose you are creating module with name of Album.
  1. Attach module with application.
    Open file i.e /config/application.config.php, Add Blog in array like below:
    return array(
         'modules' => array(
             'Application',
             'Blog'
         ),
         
     );
    
  2. create Album  folder inside the module folder.
  3. After creating the Album folder inside modules, Create below folder structure.
  4. Album/
        Module.php
        autoload_classmap.php
        autoload_function.php
        autoload_register.php
        config/
            module.config.php
        public/
            images/
            css/
            js/
        src/
            Album/
                Controller/
                    AlbumController.php
                Form/
                    AlbumForm.php
                Model/
                    Album.php 
        view/
            album/
                album/
                    index.phtml
            layout/
                layout.phtml
            error
                index.phtml
    



Question: How to attach a module in main application?
Go to File config/application.config.php, and add your module name in modules array.
See example below (We have add a module Album).
return array(
     'modules' => array(
         'Application',
         'Album'
     ),
     
 );



Question: What is Service?
A Service is an object in the module that executes complex logic of the application.
Here we do all difficult logic together and gives you easy to understand results.


Question: What are the basic steps for creating the Service?
  1. Create a folder service in-side the module and path will be similar to below:
    /module/{moduleName}/src/{moduleName}/Service/{Album}Service.php
  2. Create a model in-side the module and path will be similar to below:
    /module/{moduleName}/src/{moduleName}/Model/Post.php
  3. Add Following code in controller where you want to use.
    use {moduleName}\Service\PostServiceInterface;

    Add following in controller (you can use another variable)
    protected $postService;
     public function __construct(PostServiceInterface $postService)
         {
             $this->postService = $postService;
         }

  4. Create the Factory class (path: /module/{moduleName}/src/{moduleName}/Factory/{factoryClass}.php)
  5. Register your service in module.config.php. (Add following code)
            'service_manager' => array(
             'invokables' => array(
                 '{moduleName}\Service\{Service}' => '{moduleName}\Service\{Service}'
             )
             
  6. Register your service from module.config
    (Path: /module/Blog/config/module.config.php)
        'controllers'  => array(
             'factories' => array(
                 '{moduleName}\Controller\List' => '{moduleName}\Factory\{factoryClass}'
             )
          

Question: How to set different Db Connections for each module?
There are different module.config.php file inside each module (module/{moduleName/config/module.config.php}.
In this you you can set the database credentials.
 'db' => array(
         'driver'         => 'Pdo',
         'username'       => 'SECRET_USERNAME',  //edit this
         'password'       => 'SECRET_PASSWORD',  //edit this
         'dsn'            => 'mysql:dbname=blog;host=localhost',
         'driver_options' => array(
             \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
         )
     ),



Sunday 30 December 2018

Zend Framework 2 Session Management - Add Update Delete Session

Zend Framework 2 Session Management - Add Update Delete Session


Question: What is Zend Session?
A Session is a way to store information (in variables) to be used across multiple pages. It is mainly used to check for login information on browser and track the user activies. Zend Session is Zend libery for Session which helps to manage the session data.


Question: What is difference between Session Manager and Session Container?
Zend\Session\Container instances provide the primary API for manipulating session data. Containers are used to segregate all session data. Zend\Session\SessionManager, is a class that is responsible for all aspects of session management. It is used to initializes and configuration, storage and save handling.


Question: What is difference between Session Manager and Session Container and Session Config in One line each?
Container: The provides the core interface for managing session data.
SessionConfig: Handles setting for session config options.
SessionManager: Handles session management such as session start/exists/write/regenerate id/time-to-live/and destroy and session validation.


Question: Can you store session data in database?
Yes, we can.
For this we need to set the configuration like below:
use Zend\Db\TableGateway\TableGateway;
use Zend\Session\SaveHandler\DbTableGateway;
use Zend\Session\SaveHandler\DbTableGatewayOptions;
use Zend\Session\SessionManager;

$tableGateway = new TableGateway('session', $adapter); //this is table where session will store, you need to create the table and its model also.
$saveHandler  = new DbTableGateway($tableGateway, new DbTableGatewayOptions());
$manager      = new SessionManager();
$manager->setSaveHandler($saveHandler);


Question: How to set the Defualt Session Mangaer for Session Container?
use Zend\Session\Container;
use Zend\Session\SessionManager;

$manager = new SessionManager();
Container::setDefaultManager($manager);



Question: How to create session Object?
use Zend\Session\Container;
$sessionObj = new Container('sessinName');



Question: How to set Session value?
$sessionObj->offsetSet('email', 'email@domain.com');



Question: How to get Session value?
$sessionObj->offsetGet('email');



Question: How to check Session value exist OR Not?
$sessionObj->offsetExists('email');



Question: How to unset the session value?
$sessionObj->offsetUnset('email');



Friday 12 January 2018

Zend Framework 2 Routes

Zend Framework 2 Routes Tutorial

Question: What is routing?
Routing is the act of matching a request to a given controller.



Question: What are different type of routing?
Following are different type of routing
  1. Literal literal route is one that matches a specific string. In this one rule match to one
  2. Segment A segmented route is used for whenever your url is supposed to contain variable parameters. parameters are used to identify certain objects within your application.



Question: Give example of Literal route?
For Example:
http://domain.com/about-me
http://domain.com/contact-us
http://domain.com/terms

    'router' => array(
        'routes' => array(
        'staticpages1' => array(
             'type' => 'literal',
             'options' => array(
                 'route'    => '/about-me',
                 'defaults' => array(
                     'controller' => 'Album\Controller\Album',
                     'action'     => 'aboutme',
                 ), 
             ),
         ),            
        'staticpages2' => array(
             'type' => 'literal',
             'options' => array( 
                 'route'    => '/contactus',
                 'defaults' => array(
                     'controller' => 'Album\Controller\Album',
                     'action'     => 'contactus',
                 ),
                
             ),
         ),            
        'staticpages3' => array(
             'type' => 'literal',
             'options' => array(
                 'route'    => '/terms',
                 'defaults' => array(
                     'controller' => 'Album\Controller\Album',
                     'action'     => 'terms',
                 ),
             ),
         ), 
        ),
    ),



Question: Give example of Segment route?
For Example: http://domain.com/album
http://domain.com/album/add
http://domain.com/album/edit/1
http://domain.com/album/delete/1


    'router' => array(
        'routes' => array(
            'album' => array(
                'type' => 'segment',
                'options' => array(
                    'route' => '/album[/:action][/:id]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id' => '[0-9]+',
                    ),
                    'defaults' => array(
                        'controller' => 'Album\Controller\Album',
                        'action' => 'index',
                    ),
                ),
            ),
        ),
    ),



Question: What is database abstraction layer?
A database abstraction layer is a simplified "representation of a database" in the form of a written description or a diagram.

There are 3 abstraction layers:
  1. User model
  2. Logical Model
  3. Physical Model



Question: Why we should use database abstraction?
Once after the application development with MySQL, there is requirement to change the internal database from MySQL to SQL.
IF we have developed application with database abstraction, then we need to change the interface only.
IF we have not developed application with database abstraction, then we need to update re-write the code.


Monday 8 January 2018

Zend Framework 2 Interview questions and answers for beginners

Zend Framework 2 Interview questions and answers for beginners

Question: What is module in ZF2?
Zend Framework2 uses a module system to organised your main application-specific code within each module.
Module is separated code from main which contain its own controllers, models, forms and views, along with configuration.
File Structure of module are as following
     /module
         /Album
             /config
             /src
                 /Album
                     /Controller
                     /Form
                     /Model
             /view
                 /album
                     /album



Question: What is Service manager?
The Service Manager is an implementation of the "Service Locator" design pattern.

Keys used for the service manager should be unique across all modules, you can do
this by prepended by the module name in keys.

Service manager configuration files are merged by the module manager.
The service manager lazily instantiate services when they are needed.



Question: How to invoke a class by service manager?
$serviceManager->setInvokableClass('user_mapper', 'User\Mapper\UserMapper');



Question: How to set the routing in Zend Framework2?
In Zend framwork2, routing is set in configuration file of same module.
File path: module.config.php (Full path: \module\Album\config\module.config.php)

Example of Routing in Zend Framework
'router' => array(
    'routes' => array(
        'album' => array(
            'type' => 'segment',
            'options' => array(
                'route' => '/album[/:action][/:id]',
                'constraints' => array(
                    'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'id' => '[0-9]+',
                ),
                'defaults' => array(
                    'controller' => 'Album\Controller\Album',
                    'action' => 'index',
                ),
            ),
        ),
    ),
)

Following are the example of URL with above routing.
URL 1 : /album/index (Listing)
URL 2 : /album/add (Add Album)
URL 3 : /album/edit/10 (Edit Album )
URL 4 : /album/delete (Delete Album )

If you try to access url /album/hello, it will try to search helloAction in same controller.


Question: How to connect to mysql database in Zend Framework2?
  1. open global.php(/config/autoload/global.php)
  2. Add following before the "return array" String.
        $mysqlDbName='zf2';
        $mysqlDbHost='localhost';
        $mysqlDbUsername='root';
        $mysqlDbPassword='';
    
  3. replace the db array with following
         'db' => array(
             'driver'         => 'Pdo',
             'dsn'            => "mysql:dbname={$mysqlDbName};host={$mysqlDbHost}",
             'username' => $mysqlDbUsername,
             'password' => $mysqlDbPassword,         
             'driver_options' => array(
                 PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
             ),
         ),
        




Question: How to protect from Cross Site Scripting (XSS) vulnerabilities?
You need to use a in-built function whenever you print any data to browser.
    $htmlData='Hello World! How are you?';
    echo $this->escapeHtml($htmlData);



Question: How to direct from controller in Zend Framework2?
you can use redirect method for same.
    $this->redirect()->toUrl('/album/edit/1');



Question: How to permanent Redirect in Zend Framework2?
you can use redirect method for same.
    $this->redirect()->toUrl('/album/')->setStatusCode(301);



Question: How to temporary redirect in Zend Framework2?
you can use redirect method for same.
    $this->redirect()->toUrl('/album/')->setStatusCode(302);



Question: How to Change layout from controller in Zend Framework 2.0?
Add Following code in controller.
$this->layout('layout/custom'); //custom.phtml      
File path is : module\{module}\view\layout\custom.phtml Question: How to Change layout for module level in Zend Framework 2?
  1. Open the module.config.php of the module. (path: module\{module}\config\module.config.php)
  2. Add/Update Following code in view_manager array.
            'template_map' => array(
                'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml', //Setup the layout            
                'error/404'               => __DIR__ . '/../view/error/404.phtml',    //Setup the error        
            ),
    




Sunday 7 January 2018

Zend Framework 2 Create modules tutorial with example

Here are example of Zend Framework 2.5 module.
To run this example you must have already installed Zend Framework 2 in system.
Download the code and put unzipped folder in "modules" folder , then run SQL queries and access with /album/index


Add New Record 
URL: http://example.com/album/add
Add New Record




Listing of Records
URL: http://example.com/album
Listing of Records




Edit the record
URL: http://example.com/album/edit/4

Edit the record




Delete the record
URL: http://example.com/album/album/delete/1

Delete the record




Question: You need following SQL Query?
CREATE TABLE album (
   id int(11) NOT NULL auto_increment,
   artist varchar(100) NOT NULL,
   title varchar(100) NOT NULL,
   PRIMARY KEY (id)
 );
 INSERT INTO album (artist, title)
     VALUES  ('The  Military  Wives',  'In  My  Dreams');
 INSERT INTO album (artist, title)
     VALUES  ('Adele',  '21');
 INSERT INTO album (artist, title)
     VALUES  ('Bruce  Springsteen',  'Wrecking Ball (Deluxe)');
 INSERT INTO album (artist, title)
     VALUES  ('Lana  Del  Rey',  'Born  To  Die');
 INSERT INTO album (artist, title)
     VALUES  ('Gotye',  'Making  Mirrors');



Click below to download the module.
Download the Module



Friday 5 January 2018

How to install Zend Framework2 in Wamp Server window7?

How to install Zend Framework2 in Wamp Server

  1. Go to home directory of wamp (For Example: c://wamp/www
  2. Download composer (If not installed)
    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
    php composer-setup.php
    php -r "unlink('composer-setup.php');";
    
  3. Download the Zend Framework2
    php composer.phar create-project zendframework/skeleton-application zf2
    
    It will take few mins to download the zend framework.
  4. Copy the composer.phar to zf2 folder
    cp composer.phar zf2
    
  5. Go to zf2 directory
    cd zf2
    
  6. Virtual Host setup
    Add following code in Apache setup
    
    <virtualhost>
        DocumentRoot "D:\wamp\www\zf2\public"
        ServerName zf2.loc
        <directory public="" wamp="" www="" zf2="">
            Options FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            Allow from all
        </directory>
    </virtualhost>
    
    



Wednesday 19 April 2017

How to install Zend Framework 2 in wamp using composer?

How to install Zend Framework 2 in wamp using composer?

1. Download the composer


Go to php directory (Path:wamp\bin\php\php5.5.12) from where you can run the PHP commands.
In My Case, I goes to "D:\wamp\bin\php\php5.5.12" using cd commands.
Execute the following command.
php -r "readfile('https://getcomposer.org/installer');" | php



2. Download the Zend framework2 using composer.


You can set the path where you want to download the zf.
I have set the path to "D:/wamp/www/zf2", Please change this as per ur need.
Execute the following command.
php composer.phar create-project -sdev --repository-url="https://packages.zendframework.com" zendframework/skeleton-application "D:/wamp/www/zf2"
 


3. Virtual Host Setup


Add following code in httpd-vhosts.conf file.
My Local path: D:\wamp\bin\apache\apache2.4.9\conf\extra
<VirtualHost *:80>
    DocumentRoot "D:\wamp\www\zf2\public"
    ServerName zf2.loc
    <Directory "D:\wamp\www\zf2\public">
        Options FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>


Add following code in hosts file
My Local path is : C:\Windows\System32\drivers\etc
127.0.0.1       zf2.loc

4. ReStart wamp Server


4. Open http://zf2.loc/

It must working, if not please comment. We let u know the reason.

Monday 18 January 2016

Database Query in Zend framework 2

Database Query in Zend framework 2

Question: How to set database connection in Config file?
Create local.php file in config/autoload/ and following code .
return array(
'db' => array(
    'driver'         => 'Pdo',
    'dsn'            => 'mysql:dbname=mydb;host=localhost',
    'username'       =>'',
    'password'      =>'',
    'driver_options' => array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
    ),
),
'service_manager' => array(
    'aliases' => array(
'db' => 'Zend\Db\Adapter\Adapter',
)
));

In controller,you can get database object
$dbObj = $this->getServiceLocator()->get('db');



Question: How to connect mysql in ZF2?
$adapter = new Zend\Db\Adapter\Adapter(array(
    'driver' => 'Mysqli',
    'database' => 'mydb',
    'username' => 'root',
    'password' => ''
 ));



Question: What are different database driver provided by ZF2 ?
  1. Pdo_Mysql: MySQL through the PDO extension
  2. Pdo_Sqlite: SQLite though the PDO extension
  3. Pdo_Pgsql: PostgreSQL through the PDO extension
  4. Mysqli: The ext/mysqli driver
  5. Pgsql: The ext/pgsql driver
  6. Sqlsrv: The ext/sqlsrv driver



Question: Can we create a new Adaper for database connection? If yes, How?
With use of following you can create your own Database adapter.
use Zend\Db\Adapter\Platform\PlatformInterface;
use Zend\Db\ResultSet\ResultSet;
See Example:
use Zend\Db\Adapter\Platform\PlatformInterface;
use Zend\Db\ResultSet\ResultSet;

class Zend\Db\Adapter\Adapter {
    public function __construct($driver, PlatformInterface $platform = null, ResultSet $queryResultSetPrototype = null)
}



Question: How to custom query in zend framework 2?
$adapter->query('SELECT * FROM `users` WHERE `embid` = ? and name like "%?%" ', array(5,'rajesh'));



Question: How to join two tables in Zend Framework2?
use Zend\Db\Sql\Select();
use Zend\Db\ResultSet\ResultSet();

$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name'))
   ->join('profile', 'profile.user_id' = 'users.id'); //This is inner Join

$statement = $dbAdapter->createStatement();
$select->prepareStatement($dbAdapter, $statement);
$driverResult = $statment->execute();

$resultset = new ResultSet();
$resultset->initialize($driverResult); // can use setDataSource() for older ZF2 versions.

foreach ($resultset as $row) {
print_r($row);
}



Question: How to use Expression with query in ZF2?
new \Zend\Db\Sql\Expression("NOW()");



Question:How to Add Sub Query in ZF2
$sql = new Sql($this->_adapter);
$mainSelect = $sql->select()->from('table1');
$subQry = $sql->select()
        ->from('md_type')
        ->columns(array('orderCount' => new \Zend\Db\Sql\Expression('COUNT(table2.parent_id)')))
        ->where('table2.parent_id = table1.id');
$mainSelect->columns(
        array(
            'id', 
            'total' => new \Zend\Db\Sql\Expression('?', array($subQry)),
        )
);

$statement = $sql->prepareStatementForSqlObject($mainSelect);
$comments = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($comments)
foreach ($resultset as $row) {
print_r($row);
}



Question: How to use Group By in ZF2
$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name'))->group('users.first_name');



Question: How to use having clause in ZF2
$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name','similar_name'=>'count(first_name)'))->group('users.first_name')->having('count(first_name)>1');



Question: How to use Order By in ZF2

$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name'))->order('users.first_name asc');



Question: How to use limit in ZF2

$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name'))->order('users.first_name asc')->limit(20);


Friday 15 January 2016

Zend Soap Client and Server

Zend Soap Client and Server

Question: What is Zend\Soap\Client?
It is component which is used to send SOAP request messages to a Web service and to receive SOAP response messages from that Web service. Zend\Soap\Client takes two parameter $wsdl, $options.
$wsdl- the URI of a WSDL file.


Question: What options are available in Zend\Soap\Client?
  1. soap_version
  2. classmap
  3. encoding
  4. wsdl
  5. uri
  6. location
  7. style
  8. use
  9. login
  10. proxy credentials like proxy_host, proxy_port, proxy_login and proxy_password
  11. local_cert
  12. compression



Question: How to call Zend\Soap\Client? Give an Example?
$client = new Zend\Soap\Client("MySoapService.wsdl");
$result1 = $client->soapMethod(10);


Question: What is Zend\Soap\Server?
Zend\Soap\Server component works in the WSDL mode, it uses WSDL document to define server object behavior and transport layer.


Question: How to call Zend\Soap\Server for Non-WSDL Mode?
For WSDL Mode
$server = new Zend\Soap\Server('MySoapService.wsdl', $options);

For Non-WSDL Mode
$server = new Zend\Soap\Server(null, $options);



Question: Where is Zend_Rest in ZF2?
Zend_Rest component is removed from zf2. Now, If you want to call rest api, you can use Zend\Http\Client

Thursday 14 January 2016

Zend Framework 2 Http Client Curl - Zend\Http\Client

Zend Framework 2 Http Client Curl - Zend\Http\Client

Question: What is HttpClient?
HttpClient provide an easy way for performing HTTP Request.
Zend\Http\Client provide HTTP request, HTTP request with authentication and file upload, set header, set cookie etc.
After calling HTTP Request, Response object is return from Zend\Http\Response.


Question: Question: How to send request with GET Method?
use Zend\Http\Client;//Include this if you have not already included
$client = new Client('http://example.org/ajax/get-detail/id/100', array(
    'maxredirects' => 0,
    'timeout'      => 30
));
$response = $client->send();
echo $response->getBody();//This have response



Question: How to send request with POST Method?
$client = new Client('http://example.org/ajax/get-detail/id/100', array(
    'maxredirects' => 0,
    'timeout'      => 30
));

// Performing a POST request
$client->setMethod('POST');
//Set data
$client->setParameterGet(array(
   'first_name'  => 'Bender',
   'middle_name' => 'Bending',
   'last_name'   => 'Rodríguez',
   'made_in'     => 'Mexico',
));
$response = $client->send();
echo $response->getBody();//This have response



Question: How to send request on https URL?
Sometimes, Normally you can't send ajax request to https URL. In that case, you need to send SSL path.
$client = new Client('https://example.org/ajax/get-detail/id/100', array(
   'sslcapath' => '/etc/ssl/certs'
));



Question: How to check HTTP request is successfully.?
if ($response->isSuccess()) {
    // Here is success
}



Question: What are different Adapter available in HTTP.?
Following adapters are available.
  1. Zend\Http\Client\Adapter\Socket (default)
  2. Zend\Http\Client\Adapter\Curl
  3. Zend\Http\Client\Adapter\Test
  4. Zend\Http\Client\Adapter\Proxy



Question: How to set HTTPS transport layer in Http Request?
$client = new Client('https://example.org/ajax/get-detail/id/100', array(
    'adapter'      => 'Zend\Http\Client\Adapter\Socket',
    'ssltransport' => 'tls'
));



Question: How to set Proxy Server in Http Request?
$client = new Client('https://example.org/ajax/get-detail/id/100', array(
    'adapter'      => 'Zend\Http\Client\Adapter\Socket',
     'adapter'    => 'Zend\Http\Client\Adapter\Proxy',
    'proxy_host' => 'proxy.int.zend2.com',
    'proxy_port' => 8000,
    'proxy_user' => 'username',
    'proxy_pass' => 'mypassword'
));



Question: Why Test Adapter are used?
Test Adapter is used to Test the API where APIs are currently not available.
For this, we use Zend\Http\Client\Adapter\Test.
In the Test Adapter, we also set the response.


Question: How can we set the cookie?
$client = new Client('http://example.org/ajax/get-detail/id/100', array(
    'maxredirects' => 0,
    'timeout'      => 30
));
//Set Single cookie
$client->addCookie('flavor', 'chocolate chips');

Set cookie from String
$cookieString = \Zend\Http\Header\SetCookie::fromString('Set-Cookie: flavor=chocolate%20chips');
$client->addCookie($cookieString);

Note, setCookies are also available.
$client->setCookies(array(
     'flavor' => 'chocolate chips',
     'amount' => 10,
 ));



Question: How to set header in Curl?
You can set the Header in http_client in following way.
$client->setHeaders(array(
    Zend\Http\Header\Host::fromString('HostName: Web technology experts Notes'),    
));

$client->setHeaders(array(    
    'Accept-Encoding' => 'gzip,deflate',
    'X-Powered-By: Web technology',
));



Question: How to upload a file in Http Client?
$client->setFileUpload('/filename.text', 'FileName');



Question: How to send xml to Http Client?

For this, you need to set the content type to text/xml.
$client->setRawBody($xml);//$xml have XML content
$client->setEncType('text/xml'); //used to set the content


Question: How to pass Brower Authentication in Http Client client?

This is used when you need to pass the Authentication to call Request.
$client->setAuth('username', 'password', Zend\Http\Client::AUTH_BASIC);



Question: What is Zend\Http\ClientStatic?
Zend\Http\ClientStatic component is static HTTP client which used to Simple Get/Post Request.


Tuesday 12 January 2016

Zend Framework 2 form elements Filters and Validators

Zend Framework 2 form elements Filters and Validators


Question: How to bind Objects to Forms in ZF2?
$contact = new ArrayObject;
$contact['subject'] = '[Form] ';
$contact['message'] = 'Message';
$form    = new Contact\ContactForm;
/** This way we can bind the object to form **/
$form->bind($contact); 



Question: What happen when we bind an objects to Forms in ZF2?
  1. The composed Hydrator calls extract() on the object
  2. When isValid() is called and setData() is not called before, Hydrator extract values from the form object and do validation.



Question: How to create new Element in Form Object?
$form = new Zend\Form\Form()
//Add new element in form
$form->add(array(
     'type' => 'Email',
     'name' => 'email'
));



Question: How to extend existing form?
namespace Application\Form;
use Zend\Form\Form;
class MyNewForm extends Form{
    public function __construct($name = null){
        parent::__construct($name);
        $this->add(array(
            'name' => 'phone',
            'type' => 'text',
        ))
    }
}



Question: How to create form elements using Form Manager?
$formManager = $this->serviceLocator->get('FormElementManager');
$form = $formManager->get('Application\Form\CreatePhotoAlbum');



Question: How to create form elements and add in Form?
use Zend\Form\Element;
use Zend\Form\Form;
$checkboxElement = new Element\Checkbox('checkbox');
$checkboxElement->setLabel('Are you indian');
$checkboxElement->setUseHiddenElement(true);
$checkboxElement->setCheckedValue("yes");
$checkboxElement->setUncheckedValue("No");



Question: How to add Filter in Form?
$form = new Form\CommentForm();
$form->setInputFilter(new Form\CommentFilter());



Question: How to add validation while creating a form?
use Zend\Form\Element;
use Zend\Form\Form;

$month = new Element\Month('month');
$month->setLabel('Month')->setAttributes(array(
        'min'  => '2015-01',
        'max'  => '2017-01',
        'step' => '1', // interval is 1 month
    ));

$formObject = new Form('my-form');
$formObject->add($month);



Question: What are Form elements available in Zend Framework2?
     Button
    Captcha
    Checkbox
    Collection
    Csrf
    File
    Hidden
    Image
    Month Select
    MultiCheckbox
    Password
    Radio
    Select
    Submit
    Text
    Textarea
    Color
    Date
    DateTime
    DateTimeLocal
    Email
    Month
    Number
    Range
    Time
    Url
    Week



Question: How to display form in view phtml file?
In controller set the form.
$this->view->form = $formObject;

In View render the form.
echo $this->form;



Question: How to add input filter in Zend Form?
$inputFilterObj = new InputFilter();
$inputFilterObj->->add([
            'name' => 'profileimage',
            'type' => '\Zend\InputFilter\FileInput',
            'required' => false,
            'allow_empty' => true,
            'priority' => 300,
            'filters' => [
                ['name' => 'StripTags'],
                ['name' => 'StringTrim'],
            ],
            'validators' => [
                [
                    'name' => '\Zend\Validator\File\IsImage',
                ],
                [
                    'name' => '\Zend\Validator\File\UploadFile',
                ],
                [
                    'name' => '\Zend\Validator\File\ImageSize',
                    'options' => [
                        'minWidth' => 150,
                        'minHeight' => 120,
                    ]
                ],
                [
                    'name' => '\Zend\Validator\File\Size',
                    'options' => [
                        'max' => '2MB',
                    ]
                ],
            ]
        ]);



Question: How to make filed readonly in zend form?
$mobile = new Zend_Form_Element_Textarea('Name');
    $mobile->setLabel('mobile')
    ->addFilter('StripTags')
    ->addFilter('StringTrim')
    ->setOptions(array('class' => 'full-width'))
    ->setAttrib('rows', 2)
    ->getDecorator(('label'))->setOption('tag', 'span')
    ->setAttrib('readonly', 'true');;    



Thursday 7 January 2016

Zend Framework 2 Paginator Hydrator and Basic MVC

Zend Framework 2 Paginator Hydrator and Basic MVC

Question: What is Hydrator in Zend Framework?
Hydration is a component which is used for populating an object from a set of data.


Question: Give and example of Hydrator in Zend Framework?
use \Zend\Stdlib\Hydrator;
$hydrator = new Hydrator\ArraySerializable();
$object = new ArrayObject(array());
$data = $hydrator->extract($object);



Question: What are different implements are available in Hydrator?
Zend\Stdlib\Hydrator\ArraySerializable
Zend\Stdlib\Hydrator\ClassMethods
Zend\Stdlib\Hydrator\ObjectProperty



Question: What are use of Filter in Hydrator?
The hydrator filters, allows you to manipulate the behavior. This is especially useful, if you want to extract() your objects to the userland and strip some internals.


Question: What is Zend\Paginator?
Zend\Paginator is a component for paginating collections of data and presenting that data to users.


Question: What are different adapter available for Zend\Paginator?
  1. ArrayAdapter
  2. DbSelect
  3. Iterator
  4. NullFill


Question: What are different Configuration available for Zend\Paginator?
  1. setCurrentPageNumber
  2. setItemCountPerPage
  3. setPageRange
  4. setView


Question: How to set the caching in Zend\Paginator?
$cacheObject = StorageFactory::adapterFactory('filesystem', array(
    'cache_dir' => '/tmp',
    'ttl'       => 3600,
    'plugins'   => array( 'serializer' ),
));
\Zend\Paginator\Paginator::setCache($cacheObject);



Question: What is New MVC Layer in Zend Framework2 ?
is a brand new MVC implementation focusing on performance and flexibility in ZF2.


Question: What are the components and sub-components in New MVC Layer of Zend Framework2 ?
Following are components are used.
  1. Zend\ServiceManager
  2. Zend\EventManager
  3. Zend\Http
  4. Zend\Stdlib\DispatchableInterface

Following are sub-components are used.
  1. Zend\Mvc\Router
  2. Zend\Http\PhpEnvironment
  3. Zend\Mvc\Controller
  4. Zend\Mvc\Service
  5. Zend\Mvc\View



Question: What is application structure of Zend Framework2 ?
application_root/
    config/
        application.config.php
        autoload/
            global.php
            local.php
            // etc.
    data/
    module/
    vendor/
    public/
        .htaccess
        index.php
    init_autoloader.php




Question: What is module structure of Zend Framework2 ?

module_root<named-after-module-namespace>/
    Module.php
    autoload_classmap.php
    autoload_function.php
    autoload_register.php
    config/
        module.config.php
    public/
        images/
        css/
        js/
    src/
        <module_namespace>/
            <code files="">
    test/
        phpunit.xml
        bootstrap.php
        <module_namespace>/
            <test code="" files="">
    view/
        <dir-named-after-module-namespace>/
            <dir-named-after-a-controller>/
                &lt;.phtml files&gt;</dir-named-after-a-controller></dir-named-after-module-namespace></test></module_namespace></code></module_namespace></named-after-module-namespace>