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');;