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