Archive for the ‘Zend’ Category

Post via jQuery across domains (in this case to a Zend Controller and subsequent view) and display the results

Thursday, August 25th, 2011

the jQuery posting page, in brief:

<document…>
<head>
<script src=”http://code.jquery.com/jquery-1.5.js”></script>
</head>
<body>
<form id=”enewsform” name=”enewsform” action=”http://componentserver/controllername/post” method=”post”>
<input type=”text” name=”email” id=”email” value=”<?php echo $_REQUEST[’email’]; ?>” />
<a id=”submitsubscribe” title=”Subscribe” href=”javascript:{}” onclick=”return false;”>sign up</a>
</form>
<script src=”http://components.someserver.com/js/jquery.validation.js” type=”text/javascript”></script>
<script>
$(‘#submitsubscribe’).click(function(){
$(“#enewsform”).submit();
});

$(“#enewsform”).submit(function(event) {
event.preventDefault();
$( “#result” ).html (“submitting…”);
var $form = $( this ),
term = $form.find( ‘input[name=”email”]’ ).val(),
url = $form.attr( ‘action’ );

if($.validation.email(term)){
$.getJSON(url + “?email=” + term + “&jsoncallback=?”, function(data){
$( “#result” ).html( data[‘error’] );
if(data[‘error’]== “errormatchingstring”){
$( “#result” ).html( “Seems like it worked” );
}else{ $( “#result” ).html(data[‘error’]); }
});
}
else{ $( “#result” ).html (“Please enter your email address”); }

});
</script>

<div id=”result”></div>

// the component Zend controller in question receives the post, does whatever it does, renders its view, and we access the results from the view (don’t forget to pass data to the view with something like this:
$this-> view-> viewresult = $this-> viewData;)

<? php
echo $_REQUEST[‘jsoncallback’] . ‘(‘ . json_encode($this-> viewresult) . ‘)’;
? >

Bronto API PHP Class to Send a Contact a particular Message (Zend Helper)

Thursday, August 25th, 2011

< ? php
class
Zend_Controller_Action_Helper_BrontoSendMessage extends Zend_Controller_Action_Helper_Abstract {

public $message;
public $client;
public $viewData;
public $list;
public $now = “date(‘c’)”;
public $recipientObject;
public $email;
public $contact;
public $contactId;

private $fromName = ‘WHATEVERYOUWOULDLIKE’;
private $fromEmail = ‘YOU@YOURMAIL.COM’;

public function login(){
ini_set(“soap.wsdl_cache_enabled”, “0”);
date_default_timezone_set(‘America/New_York’);

$wsdl = “https://api.bronto.com/v4?wsdl”;
$url = “https://api.bronto.com/v4”;

$this-> client = new SoapClient($wsdl, array(‘trace’ => 1, ‘encoding’ => ‘UTF-8’));
$this-> client->__setLocation($url);

// Login
$token = “YOUR BRONTO TOKEN HERE”;
$sessionId = $this-> client->login(array(“apiToken” => $token))->return;
if (!$sessionId) {
return “Login failed”;
}
$this-> client->__setSoapHeaders(array(new SoapHeader(“http://api.bronto.com/v4”,
‘sessionHeader’,
array(‘sessionId’ => $sessionId))));

$this-> viewData[‘login’] = “logged in”;
}

public function setContact($email){
$this-> email = $email;

$filter = array(’email’ => array(array(‘operator’ => ‘EqualTo’,’value’ => $this-> email)));

$this-> contact = $this-> client->readContacts(array(‘pageNumber’ => 1,
‘includeLists’ => true,
‘filter’ => $filter,
));
if(!isset($this->contact->return->id))
{
//return ‘Email not subscribed’;
}
else
{
$this-> contactId = $this->contact->return->id;
//return $this->contactId;
}

$this-> recipientObject = array(‘type’ => ‘contact’, ‘id’ => $this->contactId);
}

public function setDelivery($messageid){
$delivery = array(‘start’ => date(‘c’),
‘messageId’ => $messageid,
‘fromName’ => $this-> fromName,
‘fromEmail’ => $this-> fromEmail,
‘recipients’ => array($this-> recipientObject),
);

$this->client->addDeliveries(array($delivery));
}
}
? >

called from another Zend Controller as a helper in this fashion:

$this-> _helper-> BrontoSendMessage->login();
$this-> _helper-> BrontoSendMessage->setContact($this-> email);
$this-> _helper-> BrontoSendMessage->setDelivery($this-> messageid);

Zend Notes: Grabbing a resource from the registry via a view helper

Wednesday, September 29th, 2010

Helper (application/views/helpers):

class Zend_View_Helper_ImageUrlHelper extends Zend_View_Helper_Abstract {
/**
* Helper to grab the path to the images directory
* @param String $imageName
* @param String $imageSize, var for possibly different size requests
*/

public function ImageUrlHelper($imageName, $imageSize) {
$config = Zend_Registry::get(‘config’);
$path = $config-> urlpaths-> productImages;
return $path . ‘/products_’ . $imageSize . ‘/’ . $imageName;
}
}

application.ini (application/configs):

urlpaths.productImages = “/path/images/product_images”

from a view (application/views/scripts/controllerName/viewName.phtml):

<?php $imgSrc = $this-> ProductImageHelper($this-> products[$i][‘products_image’], ‘100’); ?>

<img border=”0″  src=”<?php echo $imgSrc; ?>” />

framework.zend.com “Create a Model and Database Table” tutorial fixed, full working code, adapted for MySQL

Monday, September 20th, 2010

http://framework.zend.com/manual/1.10/en/learning.quickstart.create-model.html

Well, I agonized over getting this, and if you read the comments on the tutorial, many others have as well, working on my home Snow Leopard as well as on my work XP pc, and I spent countless hours looking for a post just such as this one is now, to no avail, so here it all is, hope it helps somebody:

hosts

In the event that you don’t have this done already, here is what should go in your environment’s hosts file…

Mac: /private/etc/hosts

PC:  C:\WINDOWS\system32\drivers\etc

# Setup “components” Virtual Host
<VirtualHost *:80>
ServerName project
DocumentRoot “C:\xampp\htdocs\project\public// or /Library/WebServer/Documents/project/public

<Directory “C:\xampp\htdocs\project\public” // or /Library/WebServer/Documents/project/public>
Options Indexes FollowSymLinks Includes
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>

create the database that this will use

CREATE TABLE IF NOT EXISTS `guestbook` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(32) DEFAULT NULL,
`comment` text,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

add dummy data to the database

INSERT INTO `guestbook` (`id`, `email`, `comment`, `created`) VALUES
(1, ‘ralph@schindler.com’, ‘hello’, ‘2010-09-17 00:00:00’),
(2, ‘foo@bar.com’, ‘goodbye’, ‘2010-09-17 00:00:00’);

if you haven’t done so already, create the user this app will use to connect, and give the user the priviledges they’ll need

CREATE USER ‘guestbook’@’localhost’ IDENTIFIED BY ‘guestbook’;

GRANT ALL ON ‘guestbook’ TO ‘guestbook’@’localhost’;

project/application/Bootstrap.php

<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public function _initAutoloader()
{
// Create an resource autoloader component
$autoloader = new Zend_Loader_Autoloader_Resource(array(
‘basePath’    => APPLICATION_PATH,
‘namespace’ => ‘Application’
));

// Add some resource types
$autoloader->addResourceTypes(array(
‘forms’ => array(
‘path’ => ‘forms’,
‘namespace’ => ‘Form’
),
‘models’ => array(
‘path’ => ‘models’,
‘namespace’ => ‘Model’
),
));

// Return to bootstrap resource registry
return $autoloader;
}

protected function _initActionHelpers()
{
Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH .’/helpers’);
}

protected function _initDoctype()
{
$this->bootstrap(‘view’);
$view = $this->getResource(‘view’);
$view->doctype(‘XHTML1_STRICT’);
}
}

project/public/index.php

<?php
// Define path to application directory
defined(‘APPLICATION_PATH’)
|| define(‘APPLICATION_PATH’, realpath(dirname(__FILE__) . ‘/../application’));

// Define application environment
defined(‘APPLICATION_ENV’)
|| define(‘APPLICATION_ENV’, (getenv(‘APPLICATION_ENV’) ? getenv(‘APPLICATION_ENV’) : ‘development’));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . ‘/../library’),
get_include_path(),
)));

/** Zend_Application */
require_once ‘Zend/Application.php’;

// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . ‘/configs/application.ini’
);
$application->bootstrap()
->run();

project/application/configs/application.ini

[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH “/../library”
bootstrap.path = APPLICATION_PATH “/Bootstrap.php”
bootstrap.class = “Bootstrap”
appnamespace = “Application”
resources.frontController.controllerDirectory = APPLICATION_PATH “/controllers”
resources.frontController.params.displayExceptions = 0
resources.view[] =
resources.layout.layoutPath = APPLICATION_PATH “/layouts/scripts/”

resources.db.adapter = “PDO_MYSQL”
resources.db.params.host = “localhost”
resources.db.params.username = “guestbook”
resources.db.params.password = “guestbook”
resources.db.params.dbname = “guestbook”

[staging : production]

[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1

[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1

project/application/controllers/GuestbookController.php

<?php
class GuestbookController extends Zend_Controller_Action
{

public function init()
{
/* Initialize action controller here */
}

public function indexAction()
{
$guestbook = new Application_Model_GuestbookMapper();
$guestbook->fetchAll();
//var_dump($guestbook);
$this->view->entries = $guestbook->fetchAll();
}
}

project/application/models/Guestbook.php

<?php
class Application_Model_Guestbook
{
protected $_comment;
protected $_created;
protected $_email;
protected $_id;

public function __construct(array $options = null)
{
if (is_array($options)){
$this->setOptions($options);
}
}

public function __set($name, $value)
{
$method = ‘set’ . $name;
if ((‘mapper’ == $name) || !method_exists($this, $method)){
throw new Exception(‘Invalid guestbook property’);
}
$this->$method($value);
}

public function __get($name)
{
$method = ‘get’ . $name;
if ((‘mapper’ == $name) || !method_exists($this, $method)){
throw new Exception(‘Invalid guestbook property’);
}
return $this->$method();
}

public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach($options as $key => $value){
$method = ‘set’ . ucfirst($key);
if (in_array($method, $methods)){
$this->$method($value);
}
}
}

public function setComment($text)
{
$this->_comment = (string) $text;
return $this;
}

public function getComment()
{
return $this->_comment;
}

public function setEmail($email)
{
$this->_email = (string) $email;
return $this;
}

public function getEmail()
{
return $this->_email;
}

public function setCreated($ts)
{
$this->_created = $ts;
return $this;
}

public function getCreated()
{
return $this->_created;
}

public function setId($id)
{
$this->_id = (int) $id;
return $this;
}

public function getId()
{
return $this->_id;
}
}

project/application/models/GuesbookMapper.php

<?php
class Application_Model_GuestbookMapper
{
protected $_dbTable;

public function setDbTable($dbTable)
{
if (is_string($dbTable)){
$dbTable = new $dbTable();
}
if (!$dbTable instanceof Zend_Db_Table_Abstract){
throw new Exception(‘Invalid table data gateway provided’);
}
$this->_dbTable = $dbTable;
return $this;
}

public function getDbTable()
{
if (null === $this->_dbTable){
$this->setDbTable(‘Application_Model_DbTable_Guestbook’);
}
return $this->_dbTable;
}

public function save(Application_Model_Guestbook $guestbook)
{
$data = array(
’email’    =>    $guestbook->getEmail(),
‘comment’    =>    $guestbook->getComment(),
‘created’    =>    date(‘Y-m-d H:i:s’),
);

if (null === ($id = $guestbook->getId())){
unset($data[‘id’]);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data,array(‘id = ?’ => $id));
}
}

public function find($id, Application_Model_Guestbook $guestbook)
{
$result = $this->getDbTable()->find($id);
if (0 == count($result)){
return;
}
$row = $result->current();
$guestbook->setId($row->id)
->setEmail($row->email)
->setComment($row->comment)
->setCreated($row->created);
}

public function fetchAll()
{
$resultSet = $this->getDbTable()->fetchAll();
//var_dump($resultSet);
$entries = array();
foreach ($resultSet as $row){
$entry = new Application_Model_Guestbook();
$entry->setId($row->id)
->setEmail($row->email)
->setComment($row->comment)
->setCreated($row->created);
$entries[] = $entry;
}
return $entries;
}
}

project/application/models/DbTable/Guestbook.php

<?php
class Application_Model_DbTable_Guestbook extends Zend_Db_Table_Abstract
{
/** Table name */
protected $_name    = ‘guestbook’;
}

project/application/views/scripts/guestbook/index.phtml

<p><a href=”<?php echo $this->url(
array(
‘controller’ => ‘guestbook’,
‘action’ => ‘sign’
),
‘default’,
true) ?>“>Sign Our Guestbook</a></p>

Guestbook Entries: <br />
<dl>
<?php foreach ($this->entries as $entry): ?>
<dt><?php echo $this->escape($entry->email) ?></dt>
<dd><?php echo $this->escape($entry->comment)?></dd>
<?php endforeach ?>
</dl>

final URL to hit: http://project/guestbook

PHP htaccess file serve script

Friday, April 30th, 2010

search this blog for the “htaccess” file contents to put in a directory, then use this to serve up pdf files securely from said directory:

file serve php script:

first check Zend permissions…logged in, permissions granted, user active, expirations, etc…..
then:

<?
$file = “path/path/” . $_GET[‘file’];
//$file = “Broker_Admin/Materials/Course.pdf”;
header(‘Content-type: application/pdf’);
header(“Content-Disposition: inline; filename=”.$file);
/*header(“Content-Disposition: attachment; filename=”.$file);*/
header(‘Last-Modified: ‘.gmdate(‘D, d M Y H:i:s’) . ‘ GMT’);
header(‘Cache-Control: no-store, no-cache, must-revalidate’);
header(‘Cache-Control: pre-check=0, post-check=0, max-age=0’);
header(‘Pragma: anytextexeptno-cache’, true);
header(‘Cache-control: private’);
header(‘Expires: 0’);
readfile($file);
?>

then from wherever I want to call it I call this script and pass in the file wanted.

like this:

<a href=”file_serve.php?file=Test.pdf”>Download the Test file here</a>

File is NOT accessible directly, or via this script since it first checks visitor’s SESSIONS, ZEND Permissions, that variables passed to it are set, etc. and so on…