Showing posts with label Zend Framework. Show all posts
Showing posts with label Zend Framework. 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.

Wednesday 5 June 2019

Zend Framework 3 Authentication

Zend Framework 3 Authentication

use Zend\Authentication\Adapter\DbTable\CredentialTreatmentAdapter as AuthAdapter;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Storage\Session as SessionStorage;
            
$authAdapter = new AuthAdapter(
    $this->adapter,
    'admins',
    'email',
    'password',
     'md5(?)'
);

$authAdapter
    ->setIdentity($userName)
    ->setCredential($password);
$authResult = $authAdapter->authenticate();

if($authResult->isValid()){
    $result['success']=1;
    $identity=$authResult->getIdentity();

    //Save in session
    $adminDetails=$authAdapter->getResultRowObject(array('id','email'));
    $authService = new AuthenticationService();
    $authService->setStorage(new SessionStorage('AdminLogin'));
    $authService->getStorage()->write((array)$adminDetails);
}else{
    $messages = $authResult->getMessages();
    $result['msg'] =implode(' ',$messages);
}
    


HelpFul Links
https://github.com/zendframework/zend-authentication
https://github.com/zendframework/zend-authentication/blob/master/src/AuthenticationService.php

Monday 6 May 2019

Zend 3 Interview Questions and Answers

Zend 3 Interview Questions and Answers

Question: How to print MySql query in zend framework?
$select = $this->sql->select();
echo $select->from('users')
        ->columns(array('id', 'first_name', 'last_name', 'email', 'status', 'total_events' => (`10`)))
        ->where($conds)
        ->order($orderBy);



Question: What are different type of route?
Literal routes: a literal route is one that exactly matches a specific string.
Segment routes: Segment routes allow you to define routes with variable parameters.


Question: How to disabled layout from controller in Zend Framework 3?
$view= new ViewModel();
$view->setTerminal(true);
return $view;



Question: How to print Sql Query in Zend3?
echo  $select->getSqlString($this->sql->getAdapter()->getPlatform(),\Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);



Question: Give example of Inner join, Left Join and Right join?
Inner join
$select = $this->sql->select();
$select->from(array('u'=>'users'))
        ->columns(array('id','email'))
        ->join(array('eq'=>'event_qualifiers'),"eq.user_id=u.id",array('total_events','event_type'));


Left join
$select = $this->sql->select();
$select->from(array('u'=>'users'))
        ->columns(array('id','email'))
        ->join(array('eq'=>'event_qualifiers'),"eq.user_id=u.id",array('total_events','event_type'),$select::JOIN_LEFT);


Right join
$select = $this->sql->select();
$select->from(array('u'=>'users'))
        ->columns(array('id','email'))
        ->join(array('eq'=>'event_qualifiers'),"eq.user_id=u.id",array('total_events','event_type'),$select::JOIN_RIGHT);


Question: How to autoload new module?
Once you have created the file structure for new module
1) Open the composer.json file.
2. Add the following line in psr-4 under autoload.
"Newmodule\\": "module/Newmodule/src/"


like below
"autoload": {
    "psr-4": {
        "Application\\": "module/Application/src/",
        "Album\\": "module/Album/src/"
    }
}



3. Execute following command
composer dump-autoload



Question: What are two components for databases?
A) One approach is to have "model classes" like Album represent each entity in your application
and then use mapper objects that load and save entities to the database.
B) Object-Relational Mapping (ORM) technology, such as Doctrine or Propel.


Question: What is use of config/modules.config.php?
We tell the ModuleManager that what module need to load with use of modules.config.php.


Question: What is Zend engine?
Zend Engine is a set of various components, which is used internally by PHP as a compiler.


Question: What are Decorators in the Zend framework?
Zend framework utilizes the decorator pattern to render elements and forms.


Question: What are Plugins in the Zend framework?
Zend Framework makes heavy use of plugin architectures.
Plugins allow for easy extensibility and customization of the framework while keeping your code separate from Zend Framework's code.


Question: How to check post method in zend framework?
if($this->getRequest()->isPost()){
}



Question: How to get post method in zend framework?
$postData = $this->getRequest()->getPost();



Question: How to get all GET data?
$this->getRequest()->getParams();



Question: How to redirect to another page from controller?
$this->_redirect("/users/login");



Question: What is Event Manager?
It gives the ability to create event based programming. This helps to create, inject and manage new events.


Question: What is Service Manager?
It gives the ability to consume any services (PHP classes) from anywhere with a little effort.


Question: What is Module Manager?
Ability to convert a collection of PHP classes with similar functionality into a single unit called as a module. The newly created modules can be used, maintained and configured as a single unit.


Thursday 12 October 2017

Azure video indexer - Get text from the Video


Question: What is Video Indexer API?
This API is used to Get the Visual Text from the Video. It will give you all the text that appear in the video.



Question: How to Get Text from the video?
  1. Get the API key
  2. Get the VIdeo URL from Azure OR Amazon S3 Or any public video URL.
  3. Pass the Video URL with API key and get the video Id token.
  4. Pass the video Id token with API key and get the all Text



Question: How to Get the API Key?
Follow the below link, you will get the API key which can be used further.
https://docs.microsoft.com/en-us/azure/cognitive-services/video-indexer/video-indexer-use-apis#subscribe-to-the-api


Question: How to Get the videoId token from the video?
$subScriptionKey = 'AZURE_SUBSCRIPTION_KEY_HERE';   
$videoUrl='https://foldername.blob.core.windows.net/bucketname/GV-NNokn-989-5175_360p.mp4';

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://videobreakdown.azure-api.net/Breakdowns/Api/Partner/Breakdowns?name=new%20video%20test&privacy=Private&videoUrl=".urlencode($videoUrl),
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
    "ocp-apim-subscription-key: {$subScriptionKey}",    
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

OR Using Zend Framework
$subScriptionKey = 'AZURE_SUBSCRIPTION_KEY_HERE';   
$videoUrl='https://foldername.blob.core.windows.net/bucketname/GV-NNokn-989-5175_360p.mp4';
$jsonData = '';        
$config = array(
       'adapter' => 'Zend_Http_Client_Adapter_Curl',
       'curloptions' => array(CURLOPT_FOLLOWLOCATION => true,CURLOPT_SSL_VERIFYPEER =>FALSE),            
   );
    $url='https://videobreakdown.azure-api.net/Breakdowns/Api/Partner/Breakdowns';
   $client = new Zend_Http_Client($url, $config);
   //Set the Header value
    $client->setHeaders('Content-Type', "multipart/form-data");
    $client->setHeaders('Ocp-Apim-Subscription-Key', $subScriptionKey);

    $postData = array(
    'name'=>'GV-NNokn-989-5175',
    'privacy'=>'Private',
    'videoUrl'=>$videoUrl
    );
    $client->setParameterGet($postData);

   $response = $client->request('POST'); 
   $jsonData= ($response->getBody());



Output
9a10d9d0002



Question: How to get video text from videoId token?
$subScriptionKey = 'AZURE_SUBSCRIPTION_KEY_HERE';   
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://videobreakdown.azure-api.net/Breakdowns/Api/Partner/Breakdowns/VIDEOIDTOKEN",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "ocp-apim-subscription-key: {$subScriptionKey}",
    "postman-token: 43c1c192-1de6-ac3d-42e0-b1ddc7cc0ee0"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

OR Using Zend Framework
$subScriptionKey = 'AZURE_SUBSCRIPTION_KEY_HERE';   
        $language = 'English';
        $body = 'How to you?';
        $breadDownsId='2bc89c5ec1';

        //Main Data
        $client = new Zend_Http_Client('https://videobreakdown.azure-api.net/Breakdowns/Api/Partner/Breakdowns/' . $breadDownsId, array(
            'maxredirects' => 0,
            'timeout' => 30
        ));       
        
        $client->setHeaders('Ocp-Apim-Subscription-Key', $subScriptionKey);

        $parameters = array(
            'language' => $language,
        );
        $client->setParameterGet($parameters);

        try {
            $response = $client->request('GET');
            $data = $response->getBody();
        } catch (Exception $ex) {
            $data = $ex;
        }
        echo $response->getBody();die;

Output
{
    "accountId": "2b525a6-3a5408006294",
    "id": "9a10d9d912",
    "partition": null,
    "name": "new video test",
    "description": null,
    "userName": "Ram Kumar",
    "createTime": "2017-10-12T04:41:20.8986398+00:00",
    "organization": "",
    "privacyMode": "Private",
    "state": "Processed",
    "isOwned": true,
    "isEditable": false,
    "isBase": true,
    "durationInSeconds": 1373,
    "summarizedInsights":{/* It will have data*/},
    "breakdowns":{/* It will have data*/},
    "social":{/* It will have data*/}
}




Tuesday 10 October 2017

CURL Example with Zend Framework1

CURL Example with Zend Framework1

Question: Give CURL Example with parameter in POST Method in Zend framework?
$config = array(
    'adapter' => 'Zend_Http_Client_Adapter_Curl',
    'ssltransport' => 'tls',
    'strict' => false,
    'persistent' => true,
);
$url = 'http://www.example.com';
$client = new Zend_Http_Client($url, $config);
$postArray = array('name'=>'Georage','age'=>33);
$client->setParameterPost($postArray);
$response = $client->request('POST');
echo $response->getBody();



Question: How to set Header data in CURL with Zend Framework1?
$client->setHeaders(array(
    'Host: www.example.com',
    'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0',
    'Accept: text/javascript, application/javascript, */*',
    'Accept-Language: en-gb,en;q=0.5',
    'Accept-Encoding: gzip, deflate',
    'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
    'X-Requested-With: XMLHttpRequest',
    'Referer: http://example.com'
));


Question: How to set Cookie data in CURL with Zend Framework1?
$client->setCookie('__utma', '174057141.1507422797.1392357517.1392698281.1392702703.3');
$client->setCookie('PHPSESSID', '0a12ket5d8d7otlo6uh66p658a5');



Question: How to set Content-Type in CURL with Zend Framework1?
$client->setHeaders('Content-Type', 'audio/flac');



Question: Give CURL Example with different option in Zend framework?
$config = array(
    'adapter' => 'Zend_Http_Client_Adapter_Curl',
    'ssltransport' => 'tls',
    'strict' => false,
    'persistent' => true,
);
$url = 'http://www.example.com';
$client = new Zend_Http_Client($url, $config);
$postArray = array('name'=>'Georage','age'=>33);
$client->setParameterPost($postArray);
/** set Headers **/
$client->setHeaders(array(
    'Host: www.example.com',
    'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0',
    'Accept: text/javascript, application/javascript, */*',
    'Accept-Language: en-gb,en;q=0.5',
    'Accept-Encoding: gzip, deflate',
    'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
    'X-Requested-With: XMLHttpRequest',
    'Referer: http://example.com'
));

/** set cookie **/
$client->setCookie('__utma', '174057141.1507422797.1392357517.1392698281.1392702703.3');
$client->setCookie('PHPSESSID', '0a12ket5d8d7otlo6uh66p658a5');
$response = $client->request('POST');

$data= $response->getBody();
echo $data; 



Question: How to Skip SSL Check in CURL using Zend Framework?
$url='www.example.com';
$config = array(
    'adapter' => 'Zend_Http_Client_Adapter_Curl',
    'curloptions' => array(
        CURLOPT_FOLLOWLOCATION => TRUE,
        CURLOPT_SSL_VERIFYPEER => FALSE
    ),
);
 $client = new Zend_Http_Client($url, $config);
 $response = $client->request('GET');



Question: How to pass binary data of in CURL usig Zend Framework?
$file='http://example.com/test/GM-qE2zq-1078-5525_360p.flac';
$jsonData = '';        
$config = array(
       'adapter' => 'Zend_Http_Client_Adapter_Curl',
       'curloptions' => array(CURLOPT_FOLLOWLOCATION => true,CURLOPT_SSL_VERIFYPEER =>FALSE),            
   );
    $url='https://stream.watsonplatform.net/speech-to-text/api/v1/recognize';
   $client = new Zend_Http_Client($url, $config);
   //Set the Header value
    $client->setHeaders('Content-Type', 'audio/flac');
    $client->setHeaders('Transfer-Encoding', 'chunked');            

   $client->setRawData(file_get_contents($file));
    //Set post method
   $response = $client->request('POST'); 
   $jsonData= ($response->getBody());

Saturday 2 September 2017

How to attach a CSV file to email - Zend

How to attach a CSV file to email - Zend

To send CSV in email, you must have following.
  1. Receiver email address
  2. CSV file that want to send as attachment.
  3. SMTP Credentials like SMTP USRNAME, SMTP PASSWORD, SMTP HOST, SMTP PORT



Script Code
    $toEmail='toemailaddress@domain.com'; //Receiver email address
    $subject='Email with attachment';//Email subject
    $htmlEmail='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eget nibh consectetur, mattis mauris vitae, aliquam orci. Nunc pretium tristique metus eget pharetra. Ut condimentum purus in ex varius, quis bibendum ex venenatis. Praesent leo lacus, feugiat vel neque ac, finibus ultricies velit. Nunc venenatis sem eu ullamcorper interdum. Fusce a pulvinar risus, quis viverra nulla. Donec tempus ex congue mauris elementum, eget fermentum orci dapibus. Proin erat lacus, lacinia eu volutpat quis, sagittis suscipit erat. Maecenas nulla enim, tempor ac urna id, tincidunt consectetur metus. Maecenas tincidunt, tortor quis sodales rutrum, purus mi accumsan libero, id maximus purus leo id ante. In posuere erat ipsum, sed mattis est placerat eget. Phasellus consectetur diam augue, sed luctus libero consequat quis. Praesent vel mauris nec ligula malesuada faucibus. Suspendisse ultrices nunc velit, in ultricies nibh tempus id. Integer quis nisi ipsum.'
            . 'This is html email.';


    //Email Configuration
    $config = array(
        'auth' => 'login',
        'ssl' => 'tls',
        'port' => '587',
        'username' => 'MAIL_USERNAME',
        'password' => 'MAIL_PASSWORD'
    );
    $tr = new Zend_Mail_Transport_Smtp('MAIL_HOST', $config);
    Zend_Mail::setDefaultTransport($tr);
    $mail = new Zend_Mail('UTF-8');
    $mail->setFrom(MAIL_SENDER_EMAIL, MAIL_SENDER_NAME);
    $mail->addTo($toEmail);
    $mail->setSubject($subject);
    $mail->setBodyHtml($htmlEmail);


    //Attachment Email
    //Get the contents of csv file
    $csvContent=  file_get_contents('http://example.com/projects/export-csv.csv');
    $at = new Zend_Mime_Part($csvContent);
    $at->type        = 'text/csv';
    $at->disposition = Zend_Mime::DISPOSITION_INLINE;
    $at->encoding    = Zend_Mime::ENCODING_BASE64;
    $at->filename    = 'csv-file.csv'; 

    //Attach the attachment in Email
    $mail->addAttachment($at);

    //Send Email
    $mail->send(); 




Question: How to send image as attachment in Email?
Following are attachment code.
$myImage=  file_get_contents('http://example.com/images/powered-by-georama-dark.png');
$at = new Zend_Mime_Part($myImage);
$at->type        = 'image/gif';
$at->disposition = Zend_Mime::DISPOSITION_INLINE;
$at->encoding    = Zend_Mime::ENCODING_BASE64;
$at->filename    = 'imagename.gif'; 

$mail->addAttachment($at);



Friday 27 May 2016

Upload Image from URL to S3 in Zend Framework

Upload Image from URL to S3 in Zend Framework


$imageURL = 'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEidv97qmJwUu4M0TAG5vrIuRLFN1YpSwJnDp6huR_eRyN3OeV2tKg_7hyK9adAH3ex6bAys6LZur073vkHRl3833KjuuoVwlaq3b1XfvqGUBKJo3TZZh54KkqgtAVGv9yQdSLkkCK47L-G2/s1600/Upload+image+from+URL+to+S3+in+Zend+Framework.png';
$extension = 'png';

$myAwsKey = 'AKIAP3APTHAC2DQLGJA'; //S3 AWS Key
$myAwsSecretKey = 'YJiKlVFERFuF/sadfzgS2jgj6z/Qhjkhsh'; //S3 Secret Key
$s3Media = 's3mediafolder'; //S3 Folder path

$s3 = new Zend_Service_Amazon_S3($myAwsKey, $myAwsSecretKey);
$uploadTo = 'clientProfileImages/thumb/205_test_push.png';

try {
    $s3->putFile($imageURL, "$s3Media/$uploadTo", array(
        Zend_Service_Amazon_S3::S3_ACL_HEADER => Zend_Service_Amazon_S3::S3_ACL_PUBLIC_READ,
        'x-amz-storage-class' => 'REDUCED_REDUNDANCY',
        'ContentType' => $extension
    ));
} catch (Exception $e) {
    echo $e->getMessage();
    die;
}
echo 'Image Uploaded Successfully in S3';

Wednesday 2 March 2016

How to use view helper in zend framework?

How to use view helper in zend framework?

Question: What is zend view helper?
View Helpers are common file(s) which is available in every view file.
Most of the time we kept helpers file in views/helpers/

Following the simple following steps to use view helper.
  1. Open configs\application.ini, Add Following line
    resources.view.helperPath.Application_View_Helper = APPLICATION_PATH "/views/helpers"
  2. Create General.php file in application\views\helpers (Might be need to create helpers folder)
  3. Add Following code in General.php
    class Zend_View_Helper_General extends Zend_View_Helper_Abstract {
        function General(){
            return $this;
        }
         function twice($a)
        {
            return $a * 2;
        }
        
        function thrice($a)
        {
            return $a * 3;
        }    
    }
  4. Test Following in any view files
    echo  $this->General()->twice(2);//4
    echo  $this->General()->thrice(2);//6
    echo  $this->General()->twice(3);//6
    echo  $this->General()->thrice(3);//9
    
  5. Done


If above is not working in other modules like admin, then copy/paste following function in Bootstrap.php

 protected function _initViewHelpers() {
        $this->bootstrap('layout');
        $layout = $this->getResource("layout");
        $view = $layout->getView();
        $view->addHelperPath(APPLICATION_PATH . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . 'helpers', "Application_View_Helper");
    }





Sunday 24 January 2016

Zend Framework Remember me login Form

Zend Framework Remember me login Form

Question: What is Remember Me meaning in Login Form?
When user close the browser, he logout automatically from the website due to session terminate.
When he come back on website, he need to re-login.

If we use remember me functionality, then user does not logout when he exit from website.


Question: How to use remember me in Zend Framework?
Before writing the data into session, Add following code.
Zend_Session::rememberMe(10*86400);  //Remember me for 10 days



Question: Can we use remember me with Zend_Auth?
Yes, See Example:
$result = $auth->authenticate($adapter);    
if ($result->isValid()) {
 $loginDetail = $adapter->getResultRowObject();
 $user = $adapter->getResultRowObject();   
 Zend_Session::rememberMe(7*86400); //7 days
 $namespace = new Zend_Session_Namespace('Zend_Auth'); 
 $auth->getStorage()->write($user); 
}



Question: How to keep user login even after 2 hour of inactivity?
You need to set the expiration time,
$namespace = new Zend_Session_Namespace('Zend_Auth');
$namespace->setExpirationSeconds(7*86400); // Session will expire after 7 days  



Question: What is forgetMe?
This function complements rememberMe() by writing a session cookie that has a lifetime.
Zend_Session::forgetMe(); 



Question: What is expireSessionCookie? Why It is used?
This is method of Zend_Session used for delete the session cookie in client side.

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

Friday 21 August 2015

How to redirect http to https in Zend Framework

How to redirect http to https in Zend Framework

http to https, Follow the following:
  1. Open htaccess file in /public OR /public_html.
  2. Add following code in your .htaccess at top
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
  3. Save the File .
  4. Refresh the webpage, you will see same page is opened with https.
If you are getting infinite loop, then it means you are using CloudFlare or a similar CDN. Now instead of above code, use below one.
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]



Tuesday 9 June 2015

Zend framework Disable the layout and Change the Layout in ZF1

 Zend framework Disable the layout and Change the Layout in ZF1


How to change layout from controller's action?
$this->_helper->layout->setLayout('newLayout');


How to change layout from view file?
$this->layout()->setLayout('newLayout'); 




How to disable the layout from controller's action?
$this->_helper->layout()->disableLayout(); 


How to disable the layout from view file?
$this->layout()->disableLayout(); 


How to disable the view from controller's action?
$this->_helper->viewRenderer->setNoRender(true);



Monday 8 June 2015

Zend Framework How to delete a table row from foreach loop

Zend Framework How to delete a table row from foreach loop

Scenario: I have list of messages for each user. I want to delete all the messages for an particular user. Here important part is, I don't to do something with deleting each message of user.

Problem: I don't want to use the delete function which creating new query.
As I want to do something with deleting the messages, so i can't delete all record in single query.

Solution: When we list any data from model, there is inbuilt delete function which will delete the current message from foreach loop.

See Example Below
Controller Part here we write the logic
$messageObj = new Application_Model_Messages();
$id=5;
$conds = array('userId=?'=>$id, 'status=?'=>'1', );
$fields = array('id','text');
$messages=$messageObj->getMessages($conds,$fields);
foreach($messages as $message){
    $isDeleted=$message->delete(); //This will delete the current row
    if($isDeleted){
        //you can write here code when each message deleted successfully.
    }
}

here delete(), will delete the current message.

  Model Function which will list of messages of user where each message is an object (Include this function in model).
function getMessages($conds = array(),$fields=array()) {
    try {
        $select = $this->select();
        $select->from(array('m' => 'user_messages'), $fields);
        foreach ($conds as $conIndex => $condValue) {
            $select->where($conIndex, $condValue);
        } 
        $result = $this->fetchAll($select);
        if ($result) {
            return $result;
        } else {
            return FALSE;
        }
    } catch (Exception $e) {
        echo $e->getMessage();
        return FALSE;
    }
}
In this model, you can add condition and  fields dynamically. When calling you can add custom conditions and fields.

Question: How to delete one OR Multiple Record in ZF1.12?
     function deleteRecord($tourId=0) {
         return $this->delete(array('tour_id=?' => $tourId));
    }





Tuesday 12 May 2015

Zend framework pagination with array adapter - with code snippets

Zend pagination can be implemented with used of pagination component which is available with Zend Framework v1.6.
It is so loosely coupled that you can use it wherever you want without worrying about any other component at all.

Zend framework pagination with array adapter


In zend frameowork 1.12, Zend paging component provides 5 types of Adapter and are following:
1. Array:
Use a PHP array.
2. DbSelect: Use a Zend_Db_Select instance which return an array.
3. DbTableSelect: Use a Zend_Db_Table_Select instance, which will return the instance of Zend_Db_Table_Rowset_Abstract.
4. Iterator: Use an Iterator instance.
5. Null: Do not use Zend_Paginator to manage data pagination. You can still take advantage of the pagination control feature.

Above out of 5, Here we are using first one with code snippets.



Add following code in views/scripts/mypaging.phtml (This is global file paging)
<div class="pagination" style="width:100%">
    <div style="float:left;width:28%">
    </div>
    <div style="float:right;width:70%;">
        <!-- First page link -->
        <?php if (isset($this->previous)): ?>
              <a href="/<?php echo $this->url(array('page' => $this->first)); ?>">Start</a> |
        <?php else: ?>
                <span class="disabled">Start</span> |
        <?php endif; ?>
 
        <!-- Previous page link -->
 
        <?php if (isset($this->previous)): ?>
              <a href="/<?php echo $this->url(array('page' => $this->previous)); ?>">&lt; Previous</a> |
        <?php else: ?>
            <span class="disabled">&lt; Previous</span> |
        <?php endif; ?>
        <!-- Numbered page links -->
        <?php foreach ($this->pagesInRange as $page): ?>
            <?php if ($page != $this->current): ?>
                <a href="/<?php echo $this->url(array('page' => $page)); ?>"><?php echo $page; ?></a>
            <?php else: ?>
                <?php echo $page; ?>
            <?php endif; ?>
        <?php endforeach; ?>
        <!-- Next page link -->
        <?php if (isset($this->next)): ?>
              | <a href="/<?php echo $this->url(array('page' => $this->next)); ?>">Next &gt;</a> |
        <?php else: ?>
            | <span class="disabled">Next &gt;</span> |
        <?php endif; ?>
        <!-- Last page link -->
        <?php if (isset($this->next)): ?>
              <a href="/<?php echo $this->url(array('page' => $this->last)); ?>">End</a>
        <?php else: ?>
         
        <?php endif; ?>      
    </div>
 </div>


Add Following CSS File for paging- It will design the paging and you can change as per your requirement.
.pagination li {
        border: 0;
        margin: 0;
        padding: 0;
        font-size: 11px;
        list-style: none; /* savers */
        float: left;
}

/* savers .pagination li,*/
.pagination a {
        border-right: solid 1px #DEDEDE;
        margin-right: 2px;
}

.pagination .previous-off,.pagination .next-off {
        color: #888888;
        display: block;
        float: left;
        font-weight: bold;
        padding: 3px 4px;
}

.pagination .next a,.pagination previous a {
        border: none;
        font-weight: bold;
}

.pagination .active {
        color: #000000;
        font-weight: bold;
        display: block;
        float: left;
        padding: 3px 6px; /* savers */
        border-right: solid 1px #DEDEDE;
}

.pagination a:link,.pagination a:visited {
        color: #0e509e;
        display: block;
        float: left;
        padding: 3px 6px;
        text-decoration: underline;
}

.pagination a:hover {
        text-decoration: none;
}



Add Following code in your action of controller.
This is will responsible only for paging.
$data = range(1, 100);
$page = $this->getRequest()->getParam('page', 0);
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($data));
$paginator->setCurrentPageNumber($page);//This is current page       
$paginator->setItemCountPerPage(20); //Total number of records per page
$this->view->paginator = $paginator;  



Add Following code in your view file of action.
This will list the records.

<?php if (count($this->paginator)): ?>
    <ul>
        <?php foreach ($this->paginator as $item): ?>
            <li><?php echo $item; ?></li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>

<?php
//This is used for pagination
echo $this->paginationControl($this->paginator, 'Sliding', 'my_pagination_control.phtml');
?>