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

Tuesday 5 January 2016

Zend Framework 2 Authentication and Authorization

Zend Framework 2 Authentication and Authorization

Question: What is difference between Authentication and Authorization?
Authentication is the process of determining whether someone is to be identified Or Not. In another words, whether he can login in system OR Not. Authorization is the process of determining whether he can access that particular things OR Not. In another words what section he can access OR Not. Authorization comes after the Authentication.


Question: How to set Secure Authentication?
  1. Login credentials should be encrypted like Md5 during authorization
  2. credentials must not keept in Session
  3. Protected Website from Session Hijacking and Session Fixation
  4. In Login Form use captcha


Question: What are four method available in Zend\Authentication\Result?
  1. isValid()
  2. getCode()
  3. getIdentity()
  4. getMessages()


Question: What constants are return from Zend\Authentication\Result?
  1. Result::SUCCESS
  2. Result::FAILURE
  3. Result::FAILURE_IDENTITY_NOT_FOUND
  4. Result::FAILURE_IDENTITY_AMBIGUOUS
  5. Result::FAILURE_CREDENTIAL_INVALID
  6. Result::FAILURE_UNCATEGORIZED



Question: How to change the Session NameSpace for Auth?
$auth->setStorage(new SessionStorage('someNamespace'));


Question: Can we create "Custom Storage Class" and use in Auth?
Yes, We can create our custom storage class using interface Zend\Authentication\Storage\StorageInterface. For Example:
use Zend\Authentication\Storage\StorageInterface;
class My\Storage implements StorageInterface{
}


Question: Can we create "Custom Adapters" for Auth?
Yes, We can create our custom storage class using interface Zend\Authentication\Adapter\AdapterInterfac. For Example:
use Zend\Authentication\Adapter\AdapterInterface;
class My\Auth\Adapter implements AdapterInterface{
}



Question: How to make user logout from application?
$auth->clearIdentity();



Question: What are different Adapter availble in Zend Framework2.4 for Authentication?
  1. Zend\Authentication\Adapter\DbTable
  2. Zend\Authentication\Adapter\Digest
  3. Zend\Authentication\Adapter\Http
  4. Zend\Authentication\Adapter\Ldap
  5. Zend\Authentication\Adapter\Http\FileResolver



Question: What is ACL component?
The Zend\Permissions\Acl component provides a lightweight & flexible access control list implementation for managing the access to different users.


Question: What is Resource and Role in ACL?
Resource: Resource is an object to which access is controlled. For Example Car.
Zend\Permissions\Acl\Resource\ResourceInterface is available.


Role: Role is an object that may request access to a Resource. For Example Driver
Driver can request to car means An Role can request access to a Resource.
Zend\Permissions\Acl\Role\RoleInterface is available.


Question: What is Rbac component?
Rbac component is a lightweight ACL implementation based around PHP 5.3's SPL RecursiveIterator & RecursiveIteratorIterator.
Its similar to Zend ACL component.
Rbac emphasis on roles and their permissions rather than objects/resources.




Zend Framework 2 Service Manager

Zend Framework 2 Service Manager

Question: What is Service Manager?
Service Manager is component which have lot of services and used to set/get the service on the requirement. It implemented on "Service Locator" design Pattern.


Question: What is Service Locator?
The Service Locator is a service/object locator, which are used to retrieving other objects.


Question: What is Service Locator Pattern?
Service Locator Pattern is a design Pattern which is used to locate various services. this design pattern used by "Service Locator Service" to get the appropriate service.


Question: What are Service Factories?
Instead of getting actual object instance or a class name, We can also the ServiceManager to invoke a provided factory to get the object instance.


Question: How to create Service Factories?Giv an Example?
You can also create your own serverice factory using Zend\ServiceManager\FactoryInterface and Zend\ServiceManager\ServiceLocatorInterface.
See Example
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class MyNewFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
  /** Return the data  

    Return the data **/  
       
    }
}

//Set the Factory
$serviceManager->setFactory('my-new-factory-name', new MyFactory()); 

//Get the Factory
$serviceManager->get('my-new-factory-name'));


Question: How to register an Object in Service manager?
$serviceManager->setService('new_obj_class1', new stdClass());
$serviceManager->setService('new_obj_class1'); // an instance of stdClass



Question: How to create aliases of any registered service?
$serviceManager->setService('my-object', $myObject);
$serviceManager->setAlias('my-alias1', 'my-object');
$serviceManager->setAlias('my-alias2', 'my-alias1')
/** my-object, my-alias1 and my-alias2 return same object **/



Question: What is use of setInvokableClass?
setInvokableClass allows you to tell the ServiceManager what class to instantiate when a particular service is requested.
$serviceManager->setInvokableClass('service-name', 'Fully\Qualified\ClassName');


Question: What is file location path Where we can set the configuration setting?
/module/module-name/config/module.config.php



Question: What are various service manager setting which we can set?
We can set abstract_factories, aliases,factories,invokables, services and shared.


Question: Give an example of service manager config?
return array(
    'service_manager' => array(
        'abstract_factories' => array(            
            'Module-Name\Service\FallbackFactory',
        ),
        'aliases' => array(            
            'SomeModule\Model\User' => 'User',            
            'AdminUser' => 'User',            
            'SuperUser' => 'AdminUser',
        ),
        'factories' => array(            
            'User'     => 'SomeModule\Service\UserFactory',
            'UserForm' => function ($serviceManager) {
            $formObject = new SomeModule\Form\User();
            $formObject->setInputFilter($serviceManager->get('UserInputFilter'));
            return $formObject;
            },
        ),
        'invokables' => array(
            'UserInputFilter' => 'SomeModule\InputFilter\User',
        ),
        'services' => array(
            // Auth is the service names
            // Values are objects
            'Auth' => new SomeModule\Authentication\AuthenticationService(),
        ),
        'shared' => array(            
            'UserForm' => false,
        ),
    ),
);





Thursday 31 December 2015

Zend Framework 2 Json Model understanding

Zend Framework 2 Json Model understanding


Question: How to render JSON response?
In controller use, JSONModel
public function indexAction()    {
        $result = new JsonModel(array('data'=>array(
     'key1' => 'value1',
     'key2' => 'value2',
     'key3' => 'value3',
     'key4' => 'value4',
     'key5' => 'value5'
            
        )));

        return $result;
    }

In View file, use following the encode the array.
echo Zend\Json\Json::encode($this->jsonArray, Zend\Json\Json::TYPE_ARRAY);



Question: How to JSON Encode an php object in recursive way?
$arrayData = Zend\Json\Json::encode($phpObject, true);



Question: How to convert XML to JSON?
$jsonContents = Zend\Json\Json::fromXml($xmlStringContents, true);



Question: How to get PHP Array from JSON Encoded string in view file?
$encodedValue='[1,2,3,4,5,6]';
$arrayData = Zend\Json\Json::decode($encodedValue,Zend\Json\Json::TYPE_ARRAY);
print_r($arrayData );die;


Question: How to get PHP Object from JSON Encoded string in view file?
$encodedValue='[1,2,3,4,5,6]';
$arrayData = Zend\Json\Json::decode($encodedValue,Zend\Json\Json::TYPE_OBJECT);
print_r($arrayData );die;



Question: How to display JSON Encoded string in Pretty way?
$encodedValue='[1,2,3,4,5,6]';
$arrayData = Zend\Json\Json::prettyPrint($encodedValue, array("indent" => " "));
print_r($arrayData );die;



Question: How to check Ajax Request OR Not?
if($this->getRequest()->isXmlHttpRequest())){
/** 
This is Ajax Request 
**/
}else{
/** 
This is NOT Ajax Request 
**/
}



Wednesday 30 December 2015

Zend Framework2 manage layout and view variables from controller

Zend Framework manage layout and view variables from view


Question: How to set variable to layout from controller?
Following are different three ways to set the variable from controller.
First way
public function indexAction(){ 
    $this->layout()->variableName = 'value1';
}

Second way
public function indexAction(){ 
    $this->layout()->setVariable('variableName', 'value2');
}

Third way
    public function indexAction(){ 
    $this->layout()->setVariables(array(
        'variableName1' => 'value1',
        'variableName2'  => 'value2',
    );
}

In layout File, you can access with following way.
$this->variableName1;


Question: How to set variable to view from controller in Zend Framework2
public function indexAction(){ 
return new ViewModel(array(
           'variableName3' => 'value 3',
         ));
}

in layout view, you can access with following way.
$this->$this->variableName2;



Question: How I can get access to my module config from the controller?
public function indexAction(){ 
    $config = $this->getServiceLocator()->get('Config');
}



Question: How to Change layout in the controller in Zend Framework 2.0?
public function indexAction(){ 
    $this->layout('layout/mynewlayout'); /*It will search view/layout/mynewlayout.phtml*/
}



Question: How to disable layout in zend framework 2?
public function indexAction(){ 
    $viewModel = new ViewModel();
    $viewModel->setTerminal(true);
}



Question: How to disable render view in zend framework 2?
public function indexAction()
{ 
    return false;
}




Tuesday 29 December 2015

Zend Framework 2 get params from URL

Zend Framework 2 get params from URL


Question: How to read the data from php://input?
$content = file_get_contents('php://input');
print_r(json_decode($content));



Question: How to get parameter value from GET without using Params plugin?
$parameterName1=$this->getRequest()->getRequest('parameterName2');
$parameterName2=$this->getRequest()->getRequest('parameterName2','Default Value');



Now with use of params plugins, you can get values easily from all type of request


Question: How to get parameter value from URL?
$parameterName1=$this->params()->fromQuery('parameterName1');
$parameterName2=$this->params()->fromQuery('parameterName2','Default Value');



Question: How to get all parameters value from URL?
$parameterArray=$this->params()->fromQuery();



Question: How to get parameter value from POST?
$parameterName1=$this->params()->fromPost('parameterName1');
$parameterName2=$this->params()->fromPost('parameterName2','Default Value');



Question: How to get all parameters value from POST?
$parameterArray=$this->params()->fromPost();



Question: How to get parameter value from header?
$parameterName1=$this->params()->fromHeader('parameterName1');
$parameterName2=$this->params()->fromHeader('parameterName2','Default Value');



Question: How to get parameter value from uploadedFile?
$parameterName1=$this->params()->fromFiles('parameterName1');
$parameterName2=$this->params()->fromFiles('parameterName2','Default Value');



Question: How to get parameter value from RouteMatch?
$parameterName1=$this->params()->fromRoute('parameterName1');
$parameterName2=$this->fromRoute()->fromFiles('parameterName2','Default Value');



Monday 28 December 2015

How to enable error reporting in Zend Framework 2?

How to enable error reporting in Zend Framework 2?

Question: How to enable error reporting in Zend Framework 2?
Open index.php in public (at root).
and add following line at the top.
error_reporting(E_ALL);
ini_set("display_errors", 1);



Question: How to enable error reporting in Zend Framework 2 for Development Server only?
Set the different APPLICATION_ENV value for development and production with use of .htaccess. For Example

Add following in .htaccess file in Development Server
SetEnv APPLICATION_ENV development

Add following in .htaccess file in Production Server
SetEnv APPLICATION_ENV production


Add following line in top of public/index.php
 if ($_SERVER['APPLICATION_ENV'] == 'development') {
     error_reporting(E_ALL);
     ini_set("display_errors", 1);
 }else if($_SERVER['APPLICATION_ENV'] == 'production'){
     error_reporting(0);
     ini_set("display_errors", 0);
}



Saturday 26 December 2015

What is Composer in php? - Manage the Dependencies

What is Composer in php? -  Manage the Dependencies


Question: What is Composer?
Composer is an application-level package manager for the PHP.


Question: Why Composer is used?
  1. Composer provides a standard format for managing dependencies of PHP software.
  2. Composer installs the dependencies libraries.
  3. Composer provides autoload capabilities for libraries.


Question: Where composer is used?
When we need manage the dependencies of PHP application, we can use Composer.


Question: How Composer Works?
It works commond line.


Question: Who developed the Composer?
  1. Nils Adermann.
  2. Jordi Boggiano.
.

Question: What is current stable version of Composer?
1.2.0 / July 18, 2016.


Question: In Which language, It was writeen?
PHP.


Question: What is offical website of Composer?
http://getcomposer.org/


Question: What are System Requirements for compser?
  1. PHP 5.3.2+
  2. Need git, svn or hg repository depend of composer version.


Question: What is command to download the composer?
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');"
You need curl OR openssl enable for above command.


Question: How to install the composer?
php composer.phar install



Question: How to update the composer?
php composer.phar update



Question: How to check current version of composer?
php composer.phar -V



Question: Can I used composer standard for my new project?
Yes, you can start.


Question: Is it open-source?
Yes, It is open-source.


Question: Give me sample of composer.json file?
{
    "name": "zendframework/skeleton-application",
    "description": "Skeleton Application for ZF2",
    "license": "BSD-3-Clause",
    "keywords": [
        "framework",
        "zf2"
    ],
    "homepage": "http://framework.zend.com/",
    "require": {
        "php": ">=5.3.3",
        "zendframework/zendframework": "2.3.2"
    }
}

Thursday 24 December 2015

How to install Zend Framework 2 in windows


How to install Zend Framework 2 in windows

  1. Add PHP.exe Path to Your Windows Path Variable.
    Means we need to add php.exe's path to windows path variable So that you can execute php commands.
    (My php.exe Path: E:\wamp\bin\php\php5.4.3)
    Not understand OR any Doubt 
  2. Make sure you have >=PHP5.4 Version.
  3. Now download Zend Framework 2.3.2 From https://github.com/zendframework/ZendSkeletonApplication/releases/tag/release-2.3.2
  4. Unzip this zipped file .
  5. Rename ZendSkeletonApplication to zf2.
  6. Copy this zf2 folder to E:\wamp\www
  7. Login to command prompt & Go to www folder of wamp (Path: E:\wamp\www\zf2)
  8. Now download composer with following command.
    php -r "readfile('https://getcomposer.org/installer');" | php
    If the above fails, enable php_openssl.dll in php.ini & Restart wamp Server.
  9. Now execute following command to install the composer
    php composer.phar install
  10. Apache Setup  (Path: E:\wamp\bin\apache\apache2.2.22\conf\extra)
    <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>
  11. Append following line in host File (Path:C:\Windows\System32\drivers\etc)
    127.0.0.1       zf2.loc
  12. ReStart your wamp Server.
  13. http://zf2.loc in Web Browser