Using Zend Framework 1 Service Window Azure Standalone - zend-framework

I am using zend service for window azure wrapper class standaline in my custom application. I would like to know how do i connect to my window azure storage. there seems to be no way i can specify the connection details (storage key etc)
$storageClient = new Zend_Service_WindowsAzure_Storage_Blob();
$result = $storageClient->createContainer('testcontainer');
echo 'Container name is: ' . $result->Name;
I am taking refernces from http://framework.zend.com/manual/1.12/en/zend.service.windowsazure.storage.blob.html
zend/Azure expert advice appreciated. thanks

Just add this code to the IndexController in your application
public function indexAction()
{
$auth = Zend_Auth::getInstance();
if($auth->hasIdentity())
{
$this->view->content = '<h1>Welcome to TestIndex!</h1>';
// Need to change
}
else
{
$storageClient = new Zend_Service_WindowsAzure_Storage_Blob('blob.core.windows.net', 'YOURNAME', 'YOURCODE');
$result = $storageClient->createContainer('container');
echo 'Container name is: ' . $result->Name;
var_dump($result->Name);
exit();
}
}

Related

zend session namespace not working

I am unable to access zend session in included file via layout.
what i have done so far -
//bootstrap
public function _initSession()
{
Zend_Session::start();
$test = new Zend_Session_Namespace('test');
}
//controller
public function init(){
$test = new Zend_Session_Namespace('test');
$test->abc = 'defghi';
}
//layout include file
<?php include_once( APPLICATION_PATH . '/data/ga_test.php');?>
//ga_test.php
$test = new Zend_Session_Namespace('test');
echo 'this is ' . $test->abc;
I am not able to access the variable in ga_test file. I am getting an empty variable. But if I include ga_test end of each view file then it works. Obviously I don't want to go to every view file and include ga_test.php. Can I do this via layout.
I am sure, I am doing something wrong here. Any help would be really appreciated.
Thanks

Integrating Zend Framework 1.11 with MongoDB using Doctrine ODM

Does any know of a way to integrate zend framework with Mongo using Doctrine 2 beta ODM?
I've viewed the zendcast video on integrating with Doctrine 2 ORM for MySQL but Bisna was never updated to support Mongo.
I guess I can try and hack Bisna to get it working but I'd like to know if someone else has already found a way to get it working.
It's pretty easy to write a Zend Bootstrap Resource.
Here is one I use:
<?php
namespace Cob\Application\Resource;
use Doctrine\Common\Annotations\AnnotationReader,
Doctrine\ODM\MongoDB\DocumentManager,
Doctrine\MongoDB\Connection,
Doctrine\ODM\MongoDB\Configuration,
Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver,
Doctrine\Common\EventManager;
/**
* Creates a MongoDB connection and DocumentManager instance
*
* #author Andrew Cobby <cobby#cobbweb.me>
*/
class Mongo extends \Zend_Application_Resource_ResourceAbstract
{
/**
* #return \Doctrine\ODM\MongoDB\DocumentManager
*/
public function init()
{
$options = $this->getOptions() + array(
'defaultDB' => 'my_database',
'proxyDir' => APPLICATION_PATH . '/domain/Proxies',
'proxyNamespace' => 'Application\Proxies',
'hydratorDir' => APPLICATION_PATH . '/domain/Hydrators',
'hydratorNamespace' => 'Application\Hydrators'
);
$config = new Configuration();
$config->setProxyDir($options['proxyDir']);
$config->setProxyNamespace($options['proxyNamespace']);
$config->setHydratorDir($options['hydratorDir']);
$config->setHydratorNamespace($options['hydratorNamespace']);
$config->setDefaultDB($options['defaultDB']);
$reader = new AnnotationReader();
$reader->setDefaultAnnotationNamespace('Doctrine\ODM\MongoDB\Mapping\\');
$config->setMetadataDriverImpl(new AnnotationDriver($reader, $this->getDocumentPaths()));
$evm = new EventManager();
$evm->addEventSubscriber(new SlugSubscriber());
return DocumentManager::create(new Connection(), $config, $evm);
}
public function getDocumentPaths()
{
$paths = array();
foreach(new \DirectoryIterator(APPLICATION_PATH . '/modules') as $module){
$path = $module->getPathname() . '/src/Domain/Document';
if((!$module->isDir() || $module->isDot()) || !is_dir($path)){
continue;
}
$paths[] = $path;
}
if(!count($paths)){
throw new \Exception("No document paths found");
}
return $paths;
}
}
Though you'll have to update the getDocumentPaths() method to suit your application directory structure.
I wrote my own very simple application resource plugin and container, using Guilherme's integration suite for inspiration.
I'm sure this could be much more featured in terms of capturing options but I figured I'll add those in as I need them.
See https://gist.github.com/891415

Where should I implement cache within Zend_Db?

I'm looking to implement a cache within Zend_Db, there isn't any native method to provide a cache to Zend_Db, so I'm wondering where should I do it.
I took a look to the Zend_Db_Table_Abstract (I'm extending it in a custom App_Model_DbTable_Abstract) and I found a protected method _fetch() which directly take a Zend_Db_Table_Select instance and looks like to be the last step before the adapter.
I was thinking override this method, serialize the $select object, hash it, and finally cache it, and check against each $select object provided to return the cache or an up-to-date rowset.
Is it a correct way to do?
Here is what I just did:
class App_Model_DbTable_Abstract extends Zend_Db_Table_Abstract
{
protected function _fetch(Zend_Db_Table_Select $select)
{
$hashedQuery = sha1(serialize($select->__toString()));
$cacheManager = Zend_Registry::get('Zend_Cache_Manager');
$cache = $cacheManager->getCache('database');
if (!($data = $cache->load($hashedQuery))) {
$data = parent::_fetch($select);
$cache->save($data, $hashedQuery);
}
return $data;
}
}
As far as I know, the zf create db-table <name> will always create a class inheriting Zend_Db_Table_Abstract which would make your proposal difficult to manage.
Besides, you're coupling the cache & db modules of ZF so one could argue that it's not right to place cache mechanisms under the dbtable scope. For example: you should not know where the data is being fetched from but still be able to cache it, so the process becomes this:
check cache for data, serve if found
fetch data from X (could be dbtable, could also be a Service, an XML-file, some JSON etc)
save data in cache and serve data
So although your solution makes sense now since you're only using dbtable models, it could be placed in a more suiting layer. I would check out http://www.slideshare.net/weierophinney/playdoh-modelling-your-objects-1766001 (around slide #35) for a practical solution.
Summary: the dbtable module and your code concerning it should always be about using the db.
public function indexAction()
{
// action body
$this->_helper->layout->setLayout('layout');
$db = new Zend_Db_Adapter_Pdo_Mysql(array('host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'zendtest'));
$sql = "SELECT SQL_CALC_FOUND_ROWS "
. " register.firstname, "
. " register.lastname, "
. " register.username, "
. " register.password, "
. " register.email, "
. " register.city, "
. " register.state, "
. " register.contactno "
. " FROM register register "
. " WHERE register.id = ? ";
$result = $db->fetchall($sql,1);
$result1 = "";
$cache = Zend_Registry::get('cache');
if(!$result1 = $cache->load('mydata2')) {
echo 'caching the data…..';
$cache->save($result, 'mydata2');
} else {
echo 'retrieving cache data…….';
Zend_Debug::dump($result1);
}
}
define cache array in bootstrap file then using zend DB get the data from the database and store it in cache...
next time you don't need to get data from db . you can easily and fast access that data from the cache.

Sending a SOAP message with PHP

what I'm trying to do is send a load of values captured from a form to a CRM system with SOAP and PHP. I've been reading up on SOAP for a while and I don't understand how to go about doing so, does anybody else know?
In order to do this it might be easiest to download a simple soap toolkit like 'NuSOAP' from sourceforge.
And then you would code something like the following (example submission of ISBN number):
<?php
// include the SOAP classes
require_once('nusoap.php');
// define parameter array (ISBN number)
$param = array('isbn'=>'0385503954');
// define path to server application
$serverpath ='http://services.xmethods.net:80/soap/servlet/rpcrouter';
//define method namespace
$namespace="urn:xmethods-BNPriceCheck";
// create client object
$client = new soapclient($serverpath);
// make the call
$price = $client->call('getPrice',$param,$namespace);
// if a fault occurred, output error info
if (isset($fault)) {
print "Error: ". $fault;
}
else if ($price == -1) {
print "The book is not in the database.";
} else {
// otherwise output the result
print "The price of book number ". $param[isbn] ." is $". $price;
}
// kill object
unset($client);
?>
This code snippet was taken directly from, which is also a good resource to view
http://developer.apple.com/internet/webservices/soapphp.html
Hope this helps.
You probably found a solution since then - but maybe the following helps someone else browsing for this:
soap-server.php:
<?php
class MySoapServer {
public function getMessage ()
{
return "Hello world!";
}
public function add ($n1,$n2)
{
return $n1+n2;
}
}
$option = array ('uri' => 'http://example.org/stacky/soap-server');
$server = new SoapServer(null,$option);
$server->setClass('MySoapServer');
$server->handle();
?>
and soap-client.php
<?php
$options = array ('uri' => 'http://example.org/stacky/soap-server',
'location' => 'http://localhost/soap-server.php');
$client = new SoapClient(null,$options);
echo $client ->getMessage();
echo "<br>";
echo $client ->add(41,1);
?>

Registering Zend Database Adapter in Registry

I am looking to register a reference to the main Database Adapter in the Registry during Bootstrapping so it can be used elsewhere in my site (specifically the Authorisation action).
I have implemented an ugly fix where i create a Database Table object and call the getAdapter() method on it and pass through that. However, this is a bad way of doing it and I would like it to be available via the registry.
Does anyone know how to do this? Any help or pointers in the right direction are appreciated!
I'm using Zend Framework 1.8.
If you're using Zend Framework 1.8+, and created your project with the command line tool, then it's as simple as registering your database settings in your application.ini config file.
resources.db.adapter = "PDO_MYSQL"
resources.db.params.host = "your.database.host"
resources.db.params.dbname = "database_name"
resources.db.params.username = "username"
resources.db.params.password = "password"
resources.db.isDefaultTableAdapter = true
If your database settings are preceded by resources.db you won't even need to do anything in your Bootstrap.php file because it will do it for you. Also, by setting the isDefaultTableAdapter setting to true, you can get an instance of your database adapter anywhere in your application.
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
Thanks for the replies. Ive decided to change the accepted answer and post the solution I finally used - which is insanely simple in the end!!
This is basically based on Dcaunt's comment...
In the bootstrap class..
protected function _initDb()
{
$resource = $bootstrap->getPluginResource('db');
$db = $resource->getDbAdapter();
Zend_Registry::set("db", $db);
}
Then access that elsewhere with...
$dbAdapter = Zend_Registry::get("db");
Thanks for the help and hopefully this helps someone else.
Your missing the best thing :)
If you use the Zend_Db_Table models (you should be) etc then you can set up a default adaptor - this way when you instantiate a model the DB connection it taken care off - this way you dont really need to save it in the registry or bother about connection before running a query through the model.
I do save it in the registry for later use if needed though - but I may remove this
protected function _initDB()
{
// Check that the config contains the correct database array.
if ($this->_config->db) {
// Instantiate the DB factory
$dbAdapter = Zend_Db::factory($this->_config->db);
// Set the DB Table default adaptor for auto connection in the models
Zend_Db_Table::setDefaultAdapter($dbAdapter);
// Add the DB Adaptor to the registry if we need to call it outside of the modules.
Zend_Registry::set('dbAdapter', $dbAdapter);
}
}
My 2 cents...
How to grab the default DB Adapter:
From Bootstrap:
<?php
$dbResource = $this->getPluginResource('db');
db = $dbResource->getDbAdapter();
var_dump($db);
?>
From a Controller there are two methods:
<?php
// Method 1
$bootstrap = $this->getInvokeArg('bootstrap');
$dbResource = $bootstrap->getPluginResource('db');
$dbAdapter = $dbResource->getDbAdapter();
var_dump($dbAdapter);
// Method 2
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
var_dump($dbAdapter);
?>
Check the zend-documentation at :
15.5.3.3. Storing a Database Adapter in the Registry
http://framework.zend.com/manual/en/zend.db.table.html
$db = Zend_Db::factory('PDO_MYSQL', $options);
Zend_Registry::set('my_db', $db);
// Later...
$table = new Bugs(array('db' => 'my_db'));
something like that you're looking for?
Edit:
to load your configuration from an ini-file, use:
parse_ini_file($inifile)
;configuration.ini
host = 127.0.0.1
user = username
password = blabla
;yourfile.php
$options = parse_ini_file('configuration.ini');
$db = Zend_Db::factory('PDO_MYSQL', $options);
I have a method in my bootstrap to add the adapter to the registry. I'd prefer a cleaner solution, but it works:
protected function _initRegistry(){
$this->bootstrap('db');
$db = $this->getResource('db');
$db->setFetchMode(Zend_Db::FETCH_OBJ);
Zend_Registry::set('db', $db);
}
Here is what i do:
Inside the bootstrap:
define('CONFIG_FILE', '../config/general.ini');
define('APP_MODE', 'development');
Inside the Initializer:
/**
* Initialize data bases
*
* #return void
*/
public function initDb ()
{
$options = Zend_Registry::get('conf');
$db = Zend_Db::factory($options->database);
$db->query(new Zend_Db_Expr('SET NAMES utf8'));
Zend_Registry::set('db', $db);
}
public function initConfig ()
{
if (file_exists(CONFIG_FILE) && is_readable(CONFIG_FILE)) {
$conf = new Zend_Config_Ini(CONFIG_FILE, APP_MODE);
Zend_Registry::set('conf', $conf);
} else {
throw new Zend_Config_Exception('Unable to load config file');
}
}
And finaly my config file looks like this:
[production]
database.adapter = pdo_Mysql
database.params.host = db.example.com
database.params.username = dbuser
database.params.password = secret
database.params.dbname = dbname
; Overloaded configuration from production
[development : production]
database.params.host = localhost
database.params.username = root
database.params.password =
Take a look at:
Zend_Db::Factory()
Zend_Config_Ini
Zend_Registry
If you are using Zend Framework 1.8 just do something like this in your controller/action:
class CreateorderController extends Zend_Controller_Action
{
public function testAction()
{
//more code
$users_obj = new Default_Model_Users(); //this would load the model using the Default namespace
//more code
}
}
My Defaul_Model_Users class would look something like this:
<?php
/**
* application/models/Users.php
*/
class Default_Model_Users extends Zend_Db_Table
{
protected $_table;
public function getTable()
{
if(null === $this->_table) {
$this->_table = new Default_Model_DbTable_Users();
}
return $this->_table;
}
public function fetchAll()
{
$result = $this->getTable()->fetchAll();
return $result;
}
}
And the part of the model which "interacts" directly with the database tables is found inside DbTable directory will look like this:
<?php
/**
* application/models/DbTable/Users.php
*/
class Default_Model_DbTable_Users extends Zend_Db_Table_Abstract
{
/** Table name */
protected $_name = 'users';
public function init()
{
$this->_db->setFetchMode(Zend_Db::FETCH_OBJ);
}
}
Then I would have the same application.ini generated by Zend Framework with this small addition:
resources.db.adapter = "PDO_MYSQL"
resources.db.params.host = "localhost"
resources.db.params.dbname = "mydb"
resources.db.params.username = "root"
resources.db.params.password = "password"
That is how I did without without having to change the bootstrap files.
I didn't want to use the registry to store an object that I should be able to access, so I did a little digging. It turns out that the bootstrap is registered as the front controller parameter "bootstrap", which is accessible from any of your controllers as explained in this manual page for Zend_Application.
So in your controller classes you can get the db adapter that has been defined in your ini file like this:
$bootstrap = $this->getInvokeArg('bootstrap');
$resource = $bootstrap->getPluginResource('db');
$db = $resource->getDbAdapter();