I need to lo the Zend Framework and its MVC application in a PHP script so I could do some models to query the database. The framework and some libs are loaded this way (the script was created by someone else):
/** Initialise Zend */
define( 'BRIDGE_BASE_DIR', dirname( __FILE__ ) );
set_include_path( get_include_path().PATH_SEPARATOR.BRIDGE_BASE_DIR.'/../library' );
require_once('Zend/Loader/Autoloader.php');
require_once 'Zend/Config/Ini.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace('XYz');
$autoloader->registerNamespace('Yxz');
I would like to call a model this way: Franchisee_Model_Franchisee::find($franchiseeId)
which is located under: application/modules/franchisee/models/franchisee
I tried many ways but I cannot load the full stack. Is there a simple way to load ZF in a script, including everything under application and application/modules?
UPDATE
I tried this too:
<?php
error_reporting( E_ALL & ~E_NOTICE );
/** Initialise Zend */
define( 'BRIDGE_BASE_DIR', dirname( __FILE__ ) );
set_include_path( get_include_path().PATH_SEPARATOR.BRIDGE_BASE_DIR.'/../library' );
require_once('Zend/Loader/Autoloader.php');
require_once 'Zend/Config/Ini.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace('Xyz');
$autoloader->registerNamespace('Yzx');
/** Handle arguments */
if ($argc < 2) {
echo 'LOG: ' . Zend_Date::now()->toString('YYYY-MM-ddTHH:mm:ss') . ' Please set the environment.'.PHP_EOL;
exit(1);
}
define("APPLICATION_ENV", $argv[1]);
// echo 'LOG: ' . Zend_Date::now()->toString('YYYY-MM-ddTHH:mm:ss');
// echo " Current environment is: ".APPLICATION_ENV.PHP_EOL;
/** Zend_Application */
define(APPLICATION_PATH, dirname( __FILE__ ).'/../application');
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap();
echo "Running ZF version: " . Zend_Version::VERSION;
new Admin_Contract_Table();
but I get
Fatal error: Class 'Admin_Contract_Table' not found in /Users/myuser/dev/htdocs/Admin/current/vend_bridge/zend.php on line 42
You need to bootstrap (but not run) the application as well. After what you have, add:
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap();
you may need to set APPLICATION_ENV and APPLICATION_PATH as well if you've not already.
You haven't registered your Admin namespace in the autoloader..
$autoloader->registerNamespace('Admin');
Related
I try to launch the functions of a joomla controller from an external script. The beginning of the script works very well but the use of the controller does not.
Thank you for your help,
<?php
define('_JEXEC', 1);
// this file is in a subfolder 'cron' under the main joomla folder
define('JPATH_BASE', realpath(dirname(__FILE__) . '/..'));
require_once JPATH_BASE . '/includes/defines.php';
require_once JPATH_BASE . '/includes/framework.php';
use Joomla\CMS\Factory;
// instantiate application
$app = Factory::getApplication('site');
// database connection
$db = Factory::getDbo();
jimport('joomla.application.component.controller');
JLoader::import('Article', JPATH_ROOT . '/components/com_content/controllers');
$controller = JControllerLegacy::getInstance('Article');
var_dump($controller);
I don't get anything to instantiate a controller from any other place instead of the controller's component.
So I visit the BaseController class where the getInstance() method lays. You can hack this by setting a task through application input.
<?php
define('_JEXEC', 1);
// This file is in a subfolder 'cron' under the main joomla folder
define('JPATH_BASE', realpath(dirname(__FILE__) . '/..'));
require_once JPATH_BASE . '/includes/defines.php';
require_once JPATH_BASE . '/includes/framework.php';
use Joomla\CMS\Factory;
// Instantiate application
$app = Factory::getApplication('site');
// Get the input instance
$input = $app->input;
// Database connection
$db = Factory::getDbo();
/**
* You have to provide a task for getting the controller instance.
* The `article` is the controller filename as well as the controller class's suffix
* See the controller class name is `ContentControllerArticle`
*
*/
$input->set('task', 'article.');
/**
* The first argument of the getInstance() function is the type.
* The type is the component name here.
* And you have to pass the base_path of the component through the $config argument.
*/
$controller = JControllerLegacy::getInstance('Content', ['base_path' => JPATH_ROOT . '/components/com_content']);
echo "<pre>";
print_r($controller);
echo "</pre>";
I need a little help to understand what's wrong.
I've got this problem since yesterday.Links to internal pages don't work anymore as i was reencoding my phtml files to utf-8 (without BOM).
Her's my index.php (root)
<?php
ob_start();
define('PATH', "./");
define('APPLICATION_PATH', realpath(dirname(__FILE__) . 'application/'));
define('SITE_PATH', realpath(dirname(__FILE__) . '/application/'));
define('APP_PATH', realpath(dirname(__FILE__)) . '/application/');
set_include_path(APPLICATION_PATH . 'library' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . 'application' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . 'application/controllers' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . 'application/models/' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . '' . PATH_SEPARATOR . get_include_path());
$errMsg = array();
$succMsg = array();
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
$loader->setFallbackAutoloader(true);
Zend_Session::start();
$mySession = new Zend_Session_Namespace('default');
try {
require 'application/Bootstrap.php';
} catch (Exception $exception) {
echo '<html><body><center>'
. 'An exception occured while bootstrapping the application.';
if (defined('APPLICATION_ENVIRONMENT') && APPLICATION_ENVIRONMENT != 'production') {
echo '<br /><br />' . $exception->getMessage() . '<br />'
. '<div align="left">Stack Trace:'
. '<pre>' . $exception->getTraceAsString() . '</pre></div>';
}
echo '</center></body></html>';
exit(1);
}
// DISPATCH: Dispatch the request using the front controller.
// The front controller is a singleton, and should be setup by now. We
// will grab an instance and dispatch it, which dispatches your
// application.
/* $fcontroller=Zend_Controller_Front::getInstance() ;
$router = $fcontroller->getRouter();$appRoutes=array();
$appRoutes['varun']= new Zend_Controller_Router_Route('/varun',array('module'=> 'default','controller' => 'index','action' => 'support'));
foreach($appRoutes as $key=>$cRouter){
$router->addRoute( $key, $cRouter );
}
*/
$mySession = new Zend_Session_Namespace('default');
Zend_Controller_Front::getInstance()->dispatch();
ob_flush();
Here's my .htaccess
AddHandler x-mapp-php5.5 .php .phtml
SetEnv APPLICATION_ENV development
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
Here's my application.ini
[production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
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
database.adapter = "PDO_MYSQL"
database.params.dbname = "dbname"
database.params.host = "host.com"
database.params.username = "username"
database.params.password = "password"
database.isDefaultTableAdapter = true
database.params.charset = UTF8
[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
Bootstrap.php
<?php
// APPLICATION CONSTANTS - Set the constants to use in this application.
// These constants are accessible throughout the application, even in ini
// files. We optionally set APPLICATION_PATH here in case our entry point
// isn't index.php (e.g., if required from our test suite or a script).
defined('APPLICATION_PATH') or define('APPLICATION_PATH', dirname(__FILE__));
require_once(APPLICATION_PATH.'utils/TeeImageUtils.php');
include_once(APPLICATION_PATH.'application/configs/config.inc.php');
//include_once(APPLICATION_PATH.'includes/config.php');
//include_once(APPLICATION_PATH.'paypal_pro.inc.php');
include_once(APPLICATION_PATH.'application/configs/general.php');
//include_once(APPLICATION_PATH.'application/configs/messages.php');
//include_once(APPLICATION_PATH.'facebook.php');
defined('APPLICATION_ENVIRONMENT') or define('APPLICATION_ENVIRONMENT','development');
ini_set('display_errors','on');
//error_reporting(E_ALL);
//error_reporting(0);
// FRONT CONTROLLER - Get the front controller.
// The Zend_Front_Controller class implements the Singleton pattern, which is a
// design pattern used to ensure there is only one instance of
// Zend_Front_Controller created on each request.
$frontController = Zend_Controller_Front::getInstance();
$loader = Zend_Loader_Autoloader::getInstance();
$loader->setFallbackAutoloader(true);
//Zend_Controller_Front::run('../application/controllers');
//echo "<pre>";
//print_r($frontController); die;
// CONTROLLER DIRECTORY SETUP - Point the front controller to your action
// controller directory.
$frontController->setControllerDirectory(APPLICATION_PATH .'application/controllers');
// APPLICATION ENVIRONMENT - Set the current environment
// Set a variable in the front controller indicating the current environment --
// commonly one of development, staging, testing, production, but wholly
// dependent on your organization and site's needs.
$frontController->setParam('env', APPLICATION_ENVIRONMENT);
// LAYOUT SETUP - Setup the layout component
// The Zend_Layout component implements a composite (or two-step-view) pattern
// In this call we are telling the component where to find the layouts scripts.
Zend_Layout::startMvc(APPLICATION_PATH . 'application/layouts/scripts', false,"layout");
// VIEW SETUP - Initialize properties of the view object
// The Zend_View component is used for rendering views. Here, we grab a "global"
// view instance from the layout object, and specify the doctype we wish to
// use -- in this case, XHTML1 Strict.
//$view = Zend_Layout::getMvcInstance()->getView();
//$view->setEncoding('UTF-8');
//$view->doctype('XHTML1_STRICT');
// Add helpers prefixed with Helper in helpers/
Zend_Controller_Action_HelperBroker::addPath('application/helpers/','Zend_Controller_Action_Helper_');
//$value = Zend_Controller_Action_HelperBroker::getStaticHelper('Myhelper')->displaythis();
//$value = Zend_Controller_Action_HelperBroker::getStaticHelper('Myhelper')->liscenceInfo();
// CONFIGURATION - Setup the configuration object
// The Zend_Config_Ini component will parse the ini file, and resolve all of
// the values for the given section. Here we will be using the section name
// that corresponds to the APP's Environment
$configuration = new Zend_Config_Ini(APPLICATION_PATH .'application/configs/application.ini','development');
// DATABASE ADAPTER - Setup the database adapter
// Zend_Db implements a factory interface that allows developers to pass in an
// adapter name and some parameters that will create an appropriate database
// adapter object. In this instance, we will be using the values found in the
// "database" section of the configuration obj.
$dbAdapter = Zend_Db::factory($configuration->database);
// DATABASE TABLE SETUP - Setup the Database Table Adapter
// Since our application will be utilizing the Zend_Db_Table component, we need
// to give it a default adapter that all table objects will be able to utilize
// when sending queries to the db.
$dbAdapter->query("SET NAMES 'utf8'");
Zend_Db_Table_Abstract::setDefaultAdapter($dbAdapter);
// REGISTRY - setup the application registry
// An application registry allows the application to store application
// necessary objects into a safe and consistent (non global) place for future
// retrieval. This allows the application to ensure that regardless of what
// happends in the global scope, the registry will contain the objects it
// needs.
$registry = Zend_Registry::getInstance();
$registry->configuration = $configuration;
$registry->dbAdapter = $dbAdapter;
//$helper = new Zend_Controller_Action_Helper_MWWMaster;
//$helper->preDispatch();
//Zend_Controller_Action_HelperBroker::addHelper('MWWMaster');
//$hb = new Zend_Controller_Action_HelperBroker;
//$hb->getHelper('MWWMaster');
//$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('MWWMaster');
//$viewRenderer->setView($view);
// CLEANUP - remove items from global scope
// This will clear all our local boostrap variables from the global scope of
// this script (and any scripts that called bootstrap). This will enforce
// object retrieval through the Applications's Registry
unset($frontController, $view, $configuration, $dbAdapter, $registry);
It seems to be some kind of .htaccess redirection problem but what i don't understand is that redirection performs perfectly in my admin folder.
Try adding this to your htaccess after "RewriteEngine on":
RewriteBase /clients/donqui/
My server with Joomla and API:
web/pruebasmario/joomla
web/public/api
I need use Jfactory..etc, functions plugin, componentes Joomla 2.5 in my Api.
I created a file accesjoomla.php in web/public/api:
<?php
include('../../pruebasmario/extjom.php');
$user = JFactory::getUser();
echo "Usuario " . $user->username . " con id: " . $user->id . " conectado a Joomla";
I created a file extjom.php in web/pruebasmario/joomla:
/* Initialize Joomla framework */
define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__) );
define( 'DS', DIRECTORY_SEPARATOR );
/* Required Files */
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
/* To use Joomla's Database Class */
require_once ( JPATH_BASE .DS.'libraries'.DS.'joomla'.DS.'factory.php' );
I look this: include Jfactory class in an external php file, Joomla
Access Joomla 2.5 from external script to get article by id
Joomla 2.5 Get User Data from External Script
BUT NO workk!!!!! :-((
Help me plez!
thanks!
EDIT: I managed to take a step.
Adding:
require_once (JPATH_BASE. DS. 'libraries'. DS. 'joomla'. DS. 'error'. DS. 'error.php');
I have no errors. But nothing appears. all white.
The return of the api is not returned.
What is happening?
In my app with several modules, I have a method that sends an email, the text use the url view helper to build a link. If I execute this method via browser everything works correctly, but if I run this method via a cron via shell I get this error:
Fatal error: Uncaught exception 'Zend_Controller_Router_Exception' with message 'Route default is not defined' in /path/ZendFramework-1.12.1/library/Zend/Controller/Router/Rewrite.php on line 318
Zend_Controller_Router_Exception: Route default is not defined in /path/ZendFramework-1.12.1/library/Zend/Controller/Router/Rewrite.php on line 318
Browsing the web I found this solution: http://www.dragonbe.com/2012/11/route-default-is-not-defined.html
If I do what I said in the blog error does not occur more, but at this point the generated link and 'missing the protocol and hostname, writes me a link to only the controller and action, such as "/controller/action/foo/bar"
Could you help me?
thanks
Edit
This is how I run my cron jobs:
structure:
app/
app/application
.. stuff ...
app/scripts/
app/scripts//bootstrap.php
app/scripts//cronjobs.php
app/scripts//bootstrap.php
<?php
// Define path to application directory
define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application/'));
// Ensure library/ is on include_path
set_include_path(
implode(PATH_SEPARATOR,
array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path())));
if (isset($zendOptions)) {
// using Zend_Console_Getopt to parse environment to load
require_once 'Zend/Console/Getopt.php';
try {
$getOpt = new Zend_Console_Getopt($zendOptions);
$getOpt->parse();
} catch (Zend_Console_Getopt_Exception $e) {
echo $e->getMessage() . PHP_EOL;
echo $e->getUsageMessage();
exit(1);
}
if ($getOpt->getOption('h')) {
echo $getOpt->getUsageMessage();
exit(0);
}
// Define application environment
define('APPLICATION_ENV',
$getOpt->getOption('e') ? $getOpt->getOption('e') : 'production');
} else {
// Define application environment using getenv
define('APPLICATION_ENV',
getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production');
}
// define APPLICATION_BOOTSTRAP if not defined
if (!defined('APPLICATION_BOOTSTRAP')) {
define('APPLICATION_BOOTSTRAP', true);
}
// Define standard config file
define('APPLICATION_CONFIG', APPLICATION_PATH . '/configs/application.ini');
/** Zend_Application */
require_once 'Zend/Application.php';
// Init a Zend_Application
$zendApplication = new Zend_Application(APPLICATION_ENV, APPLICATION_CONFIG);
if (APPLICATION_BOOTSTRAP) {
$zendApplication->bootstrap();
}
app/scripts/cronjobs.php
<?php
// define options for script
$zendOptions = array(
'environment|e=w' => 'Environment to use as specified in application.ini (default production)',
'test|t' => 'test cron',
'help|h' => 'Show program usage');
// bootstrap application object (default true, put to false
// if you need to bootstrap only single resources
define('APPLICATION_BOOTSTRAP', true);
// parse the options and bootstrap application if required
require_once realpath(dirname(__FILE__) . '/bootstrap.php');
/* start your script here, you'll have the following vars: */
/* #var $zendApplication Zend_Application initialized Zend_Application object */
/* #var $getOpt Zend_Console_Getopt a getopt parsed object */
error_reporting(E_ALL);
if ($getOpt->getOption('t')) {
$vhUrl = new Zend_View_Helper_Url();
$url = $vhUrl->url(array('controller' => 'foo', 'action' => 'bar'));
Zend_Debug::dump($url);
}
the debug print '/foo/bar'
I found the solution
application.ini
[production]
baseUrl = mydomain.com
[development : production]
baseUrl = mydomain.dev
[testing : production]
baseUrl = mydomain.test
Bootstrap.php
/**
* Default Routes
*/
protected function _initDefaultRoutes()
{
$frontController = Zend_Controller_Front::getInstance();
$frontController->getRouter()->addDefaultRoutes();
$options = $this->getOptions();
$frontController->setBaseUrl('http://' . $options['baseUrl']);
}
and now work!
By default helper Zend_View_Helper_Url uses Zend_Controller_Router_Rewrite which doesn't include hostname and protocol (see Zend_Controller_Router_Rewrite::assemble).
However, if you want to pass $_SERVER['HTTP_HOST'] when you execute scripts from the cli this can be done using following construction:
HTTP_HOST=example.com php /path/to/cronjob.php
Later, if you want to get your current server url, you can use Zend_View_Helper_ServerUrl
Example:
<?php
// cronjob.php
$serverUrl = new Zend_View_Helper_ServerUrl();
var_dump($serverUrl->serverUrl());
// outputs: string(18) "http://example.com"
New to Zend Framework. I been reading and found that whatever mentioned in application.ini is initialized.
1 - My Question is if I have mentioned include path for Library in ini than why I need to use include path again in index file like
// Include path
set_include_path(
BASE_PATH . '/library'
);
2 - in application.ini should I write includePaths.library like APPLICATION_PATH "/../library" OR APPLICATION_PATH "/library". Keeping in mind my index APPLICATION_PATH variable?
3 - Why should I _initView() in BootStarp file. What is the use of that code like
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(
'ViewRenderer'
);
$viewRenderer->setView($view);
application.ini mentioned
;Include path
includePaths.library = APPLICATION_PATH "/../library"
Bootstrap
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initView()
{
// Initialize view
$view = new Zend_View();
$view->doctype('XHTML1_STRICT');
$view->headTitle('My Project');
$view->env = APPLICATION_ENV;
// Add it to the ViewRenderer
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(
'ViewRenderer'
);
$viewRenderer->setView($view);
// Return it, so that it can be stored by the bootstrap
return $view;
}
}
index
<?php
define('BASE_PATH', realpath(dirname(__FILE__) . '/../'));
define('APPLICATION_PATH', BASE_PATH . '/application');
// Include path
set_include_path(
BASE_PATH . '/library'
);
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV',
(getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV')
: 'production'));
// Zend_Application
require_once 'Zend/Application.php';
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap();
$application->run();
1 and 2 are a lingering redundancy from older versions of Zend Framework. You may generally choose one method and stick to it.
Either index.php
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
or application.ini
includePaths.library = APPLICATION_PATH "/../library"
Personally, I favour the former.
Your Bootstrap.php file also seems to have a few older ZF habits. The newer application architecture includes a resource plugin for the view. Simply place this into your application.ini file
resources.view.encoding = "utf-8"
and change your bootstrap method to
// don't call this _initView as that would overwrite the resource plugin
// of the same name
protected function _initViewHelpers()
{
$this->bootstrap('view'); // ensure view resource has been configured
$view = $this->getResource('view');
$view->doctype('XHTML1_STRICT');
$view->headTitle('My Project');
$view->env = APPLICATION_ENV;
}