I have to parse a huge csv files in a Yii 1.1 Application.
Each row has to be validated and saved to the database.
I decided to use Multi Threading for this task.
So here is my code in the Controller action:
public function parseData($) {
$this->content = explode("\n", $this->content);
$thread_1 = new DatalogThread(array_slice($this->content, 0, 7000));
$thread_2 = new DatalogThread(array_slice($this->content, 7001));
$thread_1->start();
$thread_2->start();
}
And the Thread (I put it in models folder):
class DatalogThread extends Thread {
public $content;
public function __construct($content) {
$this->content = $content;
}
public function run() {
foreach ($this->content as $value) {
$row = str_getcsv($value);
$datalog = new Datalog($row);
$datalog->save();
}
}
}
The problem is that the Thread does not get access to the model file:
Fatal error: Class 'Datalog' not found in C:\xampp...\protected\models\DatalogThread.php
I tried Yii::autoload("Datalog"), but got The following error:
Fatal error: Cannot access property Yii::$_coreClasses in ...\YiiMain\framework\YiiBase.php on line 402
Yii uses a LOT of statics, this is not the best kind of code for multi-threading.
What you want to do is initialize threads that are not aware of Yii and reload it, I do not use Yii, but here's some working out to give you an idea of what to do:
<?php
define ("MY_YII_PATH", "/usr/src/yii/framework/yii.php");
include (MY_YII_PATH);
class YiiThread extends Thread {
public $path;
public $config;
public function __construct($path, $config = array()) {
$this->path = $path;
$this->config = $config;
}
public function run() {
include (
$this->path);
/* create sub application here */
}
}
$t = new YiiThread(MY_YII_PATH);
$t->start(PTHREADS_INHERIT_NONE);
?>
This will work much better ... I should think you want what yii calls a console application in your threads, because you don't want it trying to send any headers or anything like that ...
That should get you started ...
Related
I'm attempting to build a role based access control in our PHP framework. The framework is on MVC architecture so every path works on /controller/action/param. We can get the controller and action on initialization and store them in variables, $controller, $action. Now my idea is to use a class to check the permissions of this action like:
Auth::permissions($controller, $action);
Now I'm hoping I could somehow create a script which would find all public methods of controllers inside a /modules/ folder. This way I could just run a script and it would update all controller actions as a list to the database, where we would get the role permissions from. This way I could avoid inserting all controller actions manually. Getting all the controllers is very easy as the folder structure is as:
/modules
/controller
controller.php
So I can just find all subdirectories on modules and add .php in the end. My question is that can I get the file's public methods somehow?
class Example extends Controller {
public function main() {
return 'foo';
}
}
This way I could store this in the database as
example | main | role_id
Here is a little code that can help you:
<?php
class Example {
public function main() {
return 'foo';
}
private function privatefunc(){
}
public function anotherpublicfunc(){
}
}
$reflector = new ReflectionClass("Example");
foreach($reflector->getMethods() as $method){
if($method->isPublic()) {
echo "Method ".$method->name." is public".PHP_EOL;
}else{
echo "Method ".$method->name." is not public".PHP_EOL;
}
}
?>
output:
Method main is public
Method privatefunc is not public
Method anotherpublicfunc is public
If you want to get public methods of a class then you can use get_class_methods read the doc here
class Car {
public function permission_method_two() {
}
public function permission_method_three() {
}
private function private_function() {
}
}
echo '<pre>'.print_r(get_class_methods('Car'),1).'</pre>';
// prints only public methods:
Array
(
[0] => permission_method_two
[1] => permission_method_three
)
You can follow convention:
- each public methods start without lowdash
- each private and protected method start with lowdash
Example
class Example
{
public function publicMethod()
{
}
private function _privateMethod()
{
}
protected function _protectedMethod()
{
}
}
and then use http://php.net/manual/ru/function.get-class-methods.php
foreach(get_class_methods('Example') as $methodName){
if(strpos($methodName, '_') !== 0) $publicMethod[] = $methodName;
}
I currently have a manual method for registering helpers into my base connection class which goes pretty much as follows:
class db_con
{
// define the usual suspect properties..
public $helpers; // helper objects will get registered here..
public function __construct()
{
// fire up the connection or die trying
$this->helpers = (object) array();
}
public function __destruct()
{
$this->helpers = null;
$this->connection = null;
}
// $name = desired handle for the helper
// $helper = name of class to be registered
public function register_helper($name, $helper)
{
if(!isset($this->helpers->$name, $helper))
{
// tack on a helper..
$this->helpers->$name = new $helper($this);
}
}
// generic DB interaction methods follow..
}
Then a helper class such as..
class user_auth
{
public function __construct($connection){ }
public function __destruct(){ }
public function user_method($somevars)
{
// do something with user details
}
}
So after creating the $connection object, i would then manually register a helper like so:
$connection->register_helper('users', 'user_auth');
Now my question is, could I somehow autoload helper classes inside the base connection class? (within the register_helper() method or similar) Or am I limited to loading them manually or via an external autoloader of some form?
My apologies if this question has been answered elsewhere, but I just haven't found it (not for lack of trying) and I haven't any real experience autoloading anything yet.
Any help or pointers greatly appreciated, thanks in advance! :)
EDIT: As per Vic's suggestion this is the working solution I came up with for the register method..
public function register_handlers()
{
$handler_dir = 'path/to/database/handlers/';
foreach (glob($handler_dir . '*.class.php') as $handler_file)
{
$handler_bits = explode('.', basename($handler_file));
$handler = $handler_bits[0];
if(!class_exists($handler, false))
{
include_once $handler_file;
if(!isset($this->handle->$handler, $handler))
{
$this->handle->$handler = new $handler($this);
}
}
}
}
This appears to include and register the objects absolutely fine for now, whether this solution is a "good" one or not, I can't know without more input or testing.
The code could look something like below, but why would you need this?
public function register_helper($name, $helper)
{
if(!isset($this->helpers->$name, $helper))
{
$this->load_class($helper);
// tack on a helper..
$this->helpers->$name = new $helper($this);
}
}
private function load_class($class)
{
if( !class_exists($class, false) ) {
$class_file = PATH_SOME_WHERE . $class . '.php';
require $class_file;
}
}
Well, I don't know if this post have the correct title. Feel free to change it.
Ok, this is my scenario:
pluginA.php
function info(){
return "Plugin A";
}
pluginB.php
function info(){
return "Plugin B";
}
Finally, I have a plugin manager that is in charge of import all plugins info to pool array:
Manager.php
class Manager
{
protected $pool;
public function loadPluginsInfo()
{
$plugin_names = array("pluginA.php", "pluginB.php");
foreach ($plugin_names as $name)
{
include_once $name;
$this->pool[] = info();
}
}
}
The problem here is that when I print pool array it only show me the info on the first plugin loaded. I supposed that the file inclusing override the info because it still calling the info() method from the first include.
Is there a way to include the info of both plugins having the info() function with the same name for all plugins files?
Thank you in advance
PS: a fatal cannot redeclare error is never hurled
you can use the dynamic way to create plugin classes
plugin class
class PluginA
{
public function info()
{
return 'info'; //the plugin info
}
}
manager class
class Manager
{
protected $pool;
public function loadPluginsInfo()
{
$plugin_names = array("pluginA", "pluginB"); //Plugin names
foreach ($plugin_names as $name)
{
$file = $name . '.php';
if(file_exists($file))
{
require_once($file); //please use require_once
$class = new $name(/* parameters ... */); //create new plugin object
//now you can call the info method like: $class->info();
}
}
}
}
Are you sure the interpreter isn't choking w/ a fatal error? It should be since you're trying to define the info function twice here.
There are many ways to achieve what you want, one way as in #David's comment above would be to use classes, eg.
class PluginA
{
function info() { return 'Plugin A'; }
}
class PluginB
{
function info() { return 'Plugin B'; }
}
then the Manager class would be something like this:
class Manager
{
protected $pool;
public function loadPluginsInfo()
{
$plugin_names = array("PluginA", "PluginB");
foreach ($plugin_names as $name)
{
include_once $name . '.php';
$this->pool[] = new $name();
}
}
}
Now you have an instance of each plugin class loaded, so to get the info for a plugin you would have $this->pool[0]->info(); for the first plugin. I would recommend going w/ an associative array though so you can easily reference a given plugin. To do this, the assignment to the pool would become:
$this->pool[$name] = new name();
And then you can say:
$this->pool['PluginA']->info();
for example.
There are many other ways to do it. Now that 5.3 is mainstream you could just as easily namespace your groups of functions, but I would still recommend the associative array for the pool as you can reference a plugin in constant time, rather than linear.
I have a Zend Framework application based on the quick-start setup.
I've gotten the demos working and am now at the point of instantiating a new model class to do some real work. In my controller I want to pass a configuration parameter (specified in the application.ini) to my model constructor, something like this:
class My_UserController extends Zend_Controller_Action
{
public function indexAction()
{
$options = $this->getFrontController()->getParam('bootstrap')->getApplication()->getOptions();
$manager = new My_Model_Manager($options['my']);
$this->view->items = $manager->getItems();
}
}
The example above does allow access to the options, but seems extremely round-about. Is there a better way to access the configuration?
I always add the following init-method to my bootstrap to pass the configuration into the registry.
protected function _initConfig()
{
$config = new Zend_Config($this->getOptions(), true);
Zend_Registry::set('config', $config);
return $config;
}
This will shorten your code a little bit:
class My_UserController extends Zend_Controller_Action
{
public function indexAction()
{
$manager = new My_Model_Manager(Zend_Registry::get('config')->my);
$this->view->items = $manager->getItems();
}
}
Since version 1.8 you can use the below code in your Controller:
$my = $this->getInvokeArg('bootstrap')->getOption('my');
Alternatively, instead of using Zend_Registry you could also create a singleton Application class that will contain all application info, with public member functions that allow you to access the relevant data. Below you can find a snippet with relevant code (it won't run as is, just to give you an idea how it can be implemented) :
final class Application
{
/**
* #var Zend_Config
*/
private $config = null;
/**
* #var Application
*/
private static $application;
// snip
/**
* #return Zend_Config
*/
public function getConfig()
{
if (!$this->config instanceof Zend_Config) {
$this->initConfig();
}
return $this->config;
}
/**
* #return Application
*/
public static function getInstance()
{
if (self::$application === null) {
self::$application = new Application();
}
return self::$application;
}
/**
* Load Configuration
*/
private function initConfig()
{
$configFile = $this->appDir . '/config/application.xml';
if (!is_readable($configFile)) {
throw new Application_Exception('Config file "' . $configFile . '" is not readable');
}
$config = new Zend_Config_Xml($configFile, 'test');
$this->config = $config;
}
// snip
/**
* #param string $appDir
*/
public function init($appDir)
{
$this->appDir = $appDir;
$this->initConfig();
// snip
}
public function run ($appDir)
{
$this->init($appDir);
$front = $this->initController();
$front->dispatch();
}
}
Your bootstrap would look like this :
require 'Application.php';
try {
Application::getInstance()->run(dirname(dirname(__FILE__)));
} catch (Exception $e) {
header("HTTP/1.x 500 Internal Server Error");
trigger_error('Application Error : '.$e->getMessage(), E_USER_ERROR);
}
When you want to access the configuration you would use the following :
$var = Application::getInstance()->getConfig()->somevar;
In most ZF apps, the application object is declared in the global scope (see public/index.php in apps created with ZFW_DISTRIBUTION/bin/zf.sh).
It's not exactly the ZF way, but you can access the object with $GLOBALS['application'].
It kinda feels like cheating, but if you're after performance, this will likely be the quickest option.
$manager = new My_Model_Manager($GLOBALS['application']->getOption('my'));
$this->getInvokeArg('bootstrap')->getOptions();
// or
$configDb = $this->getInvokeArg('bootstrap')->getOption('db');
I've define a short hand in some place I require_once() in the beginning of boostrap:
function reg($name, $value=null) {
(null===$value) || Zend_Registry::set($name, $value);
return Zend_Registry::get($name);
}
and in the bootstrap I have a:
protected function _initFinal()
{
reg('::app', $this->getApplication());
}
then I can get the Application instance anywhere by use:
$app = reg('::app');
A really simple way to access the configuration options is by directly accessing the globally defined $application variable.
class My_UserController extends Zend_Controller_Action {
public function indexAction() {
global $application;
$options = $application->getOptions();
}
}
I'm working through Practical Web 2.0 Appications currently and have hit a bit of a roadblock. I'm trying to get PHP, MySQL, Apache, Smarty and the Zend Framework all working correctly so I can begin to build the application. I have gotten the bootstrap file for Zend working, shown here:
<?php
require_once('Zend/Loader.php');
Zend_Loader::registerAutoload();
// load the application configuration
$config = new Zend_Config_Ini('../settings.ini', 'development');
Zend_Registry::set('config', $config);
// create the application logger
$logger = new Zend_Log(new Zend_Log_Writer_Stream($config->logging->file));
Zend_Registry::set('logger', $logger);
// connect to the database
$params = array('host' => $config->database->hostname,
'username' => $config->database->username,
'password' => $config->database->password,
'dbname' => $config->database->database);
$db = Zend_Db::factory($config->database->type, $params);
Zend_Registry::set('db', $db);
// handle the user request
$controller = Zend_Controller_Front::getInstance();
$controller->setControllerDirectory($config->paths->base .
'/include/Controllers');
// setup the view renderer
$vr = new Zend_Controller_Action_Helper_ViewRenderer();
$vr->setView(new Templater());
$vr->setViewSuffix('tpl');
Zend_Controller_Action_HelperBroker::addHelper($vr);
$controller->dispatch();
?>
This calls the IndexController. The error comes with the use of this Templater.php to implement Smarty with Zend:
<?php
class Templater extends Zend_View_Abstract
{
protected $_path;
protected $_engine;
public function __construct()
{
$config = Zend_Registry::get('config');
require_once('Smarty/Smarty.class.php');
$this->_engine = new Smarty();
$this->_engine->template_dir = $config->paths->templates;
$this->_engine->compile_dir = sprintf('%s/tmp/templates_c',
$config->paths->data);
$this->_engine->plugins_dir = array($config->paths->base .
'/include/Templater/plugins',
'plugins');
}
public function getEngine()
{
return $this->_engine;
}
public function __set($key, $val)
{
$this->_engine->assign($key, $val);
}
public function __get($key)
{
return $this->_engine->get_template_vars($key);
}
public function __isset($key)
{
return $this->_engine->get_template_vars($key) !== null;
}
public function __unset($key)
{
$this->_engine->clear_assign($key);
}
public function assign($spec, $value = null)
{
if (is_array($spec)) {
$this->_engine->assign($spec);
return;
}
$this->_engine->assign($spec, $value);
}
public function clearVars()
{
$this->_engine->clear_all_assign();
}
public function render($name)
{
return $this->_engine->fetch(strtolower($name));
}
public function _run()
{ }
}
?>
The error I am getting when I load the page is this:
Fatal error: Call to a member function fetch() on a non-object in /var/www/phpweb20/include/Templater.php on line 60
I understand it doesn't see $name as an object, but I don't know how to go about fixing this. Isn't the controller supposed to refer to the index.tpl? I haven't been able to discover what the $name variable represents and how to fix this to get the foundation working.
Any help you have is much appreciated!
The problem isn't with the $name variable but rather with the $_engine variable. It's currently empty. You need to verify that the path specification to Smarty.class.php is correct.
You might try this to begin your debugging:
$this->_engine = new Smarty();
print_r($this->_engine);
If it turns out that $_engine is correct at that stage then verify that it is still correctly populated within the render() function.
Zend has an example of creating a templating system which implements the Zend_View_Interface here: http://framework.zend.com/manual/en/zend.view.scripts.html#zend.view.scripts.templates.interface
That might save you some time from trying to debug a custom solution.
removing the __construct method, from the class, solved the similar issue I was facing.
Renaming __construct() to Tempater() worked for me.