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

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>