access class from other class codeigniter - php

I have this class that I made as a library in codeigniter
class Openstack{
function __construct($params = array())
{
//namespace OpenCloud;
// note that we have to define these defaults BEFORE including the
// connection class
define('RAXSDK_OBJSTORE_NAME','cloudFiles');
define('RAXSDK_OBJSTORE_REGION','ORD');
require_once('lib/rackspace.php');
// these hold our environment variable settings
define('AUTHURL', 'https://identity.api.rackspacecloud.com/v2.0/');
define('USERNAME', "#####");
define('TENANT', "$$$$$");
define('APIKEY', "asdfasdfasdfasdfasdfasdfasdf");
// establish our credentials
$connection = new Rackspace(AUTHURL,
array( 'username' => USERNAME,
'tenantName' => TENANT,
'apiKey' => APIKEY ));
$ostore = $connection->ObjectStore();...
The problem is, when I call a function using:
public function test_upload(){
$this->load->library('opencloud/openstack');
$this->openstack->upload_file("thisworks.pdf", "static/news/10_12.pdf");
}
I get an error saying the class Rackspace isn't found pointing to the line above where I have new Rackspace...
Within the rackspace.php there is a clas name called Rackspace
class Rackspace extends OpenStack{ ...
I have no idea why it can't find it... I know it's loading the file, because I tried to echo something out in there and it showed up....
Any idea what's happening?
EDIT: At the top of the rackspace.php file there is a
namespace OpenCloud;
I don't have that in my library file class Openstack I made... When I put it in there then I got an error "Non-existent class: Openstack"

Related

How to use a global constant instead of a class constant in PHP version 5.6

I'm using Monolog to create my app's logging system. In the core app file, after I create a new Monolog object, I need to select the log level that I want to print in the log file. I want to use a global constant LOG_LEVEL which could be 'DEBUG', 'INFO', etc. I need the Monolog class to treat its value as a class constant.
// content of config.php
// Here I declare the constants in a separate file called 'config.php'
define("LOG_FILE", "patch/to/my/log.log");
define("LOG_LEVEL", "ERROR");
// content of app.php
require 'config.php';
require 'vendor/autoload.php';
$container['logger'] = function($c) {
$logger = new \Monolog\Logger('logger');
error_log('log level ' . LOG_LEVEL); // prints 'log level ERROR'
$fileHandler = new \Monolog\Handler\StreamHandler(LOG_FILE, $logger::LOG_LEVEL); // here I get the error 'Undefined class constant LOG_LEVEL'
//the normal syntax would be '$logger::ERROR' in this case and that works fine
$logger->pushHandler($fileHandler);
return $logger;
};
I need the 'LOG_LEVEL' constant to be used as 'ERROR' by the monolog class, not as 'LOG_LEVEL'. What am I doing wrong here, been searching an answer for hours now without any luck.
You are now doing $logger::LOG_LEVEL, which is taking the 'LOG_LEVEL' out of the class whichever $logger is (in this case a \Monolog\Logger). That doesn't have a static variable named LOG_LEVEL, thus you get the undefined.
You have just have 'LOG_LEVEL' defined, out of any class, so:
$fileHandler = new \Monolog\Handler\StreamHandler(LOG_FILE, LOG_LEVEL);
Fancy solution:
You could do a static class and include that in your main page:
Class CONFIG {
public static $LOG_LEVEL = 'default Value';
}
// Then you can use this anywhere:
CONFIG::$LOG_LEVEL
$fileHandler = new \Monolog\Handler\StreamHandler(LOG_FILE, CONFIG::$LOG_LEVEL);
The advantage of this is having only one file for configs, not scattered across all kinds of files, which'll become very annoying very fast.
Make a static class and include that...
class GLOBALCONF{
public static $VALUE= 'Something in here';
}
// Use it where you want
GLOBALCONF::$VALUE
You're making this more complicated than it needs to be. Monolog has a function to convert an error level as as string to its own internal value. Just change your code to this:
$fileHandler = new \Monolog\Handler\StreamHandler(LOG_FILE, $logger::toMonologLevel(LOG_LEVEL));
You can also use Logger::getLevels() like the following:
$log_level = $logger->getLevels()[LOG_LEVEL];
$fileHandler = new ...StreamHandler(LOG_FILE, $log_level);

Zend xmlrpc error

I have this error with Zend (v1) XmlRpc client :
Uncaught exception 'Zend_XmlRpc_Client_FaultException' with message 'Failed to parse response'.
It's the error status 651.
The call never reaches the class/method requested, it seems that the call is not fired like it was blocked or something. I'm in debug on the method called and it's not triggered.
PHP version is 5.4.
EDIT
Here is the code :
Caller class :
require_once 'library/Zend/XmlRpc/Client.php';
class FrontService
{
private $client;
public function __construct($xmlRpc)
{
$this->client = new Zend_XmlRpc_Client($xmlRpc);
}
public function call($name, $params = array())
{
return $this->client->call($name, $params);
}
}
Call to the class :
$this->_fs = new FrontService(HM_Config::getParam("amf-url"));
$editos = $this->_fs->call('getEdito',$params_home);
Code called :
include_once realpath(dirname(__FILE__) .'/..')
.'/application/bootstrap.php';
require_once '_config.php';
require_once 'DirectDbConnectionV2.php';
class FrontGateway extends DirectDbConnectionV2
{
public static $smStatic;
function __construct()
{
mysql_query("SET NAMES 'utf8'");
$this->sm = self::$smStatic;
$this->log = new Log();
$this->log->set_file('amfDbConnection');
$this->log->write('construct bordel');
}
}
FrontGateway::$smStatic = $sm;
$controllerManager = $sm->get('EditoWebsiteMVC\ControllerManager');
$controllerManager->run('EditoWebsite\Controller\UIGateway', 'xmlRpc');
Code that should be executed :
namespace EditoWebsite\Controller;
use EditoWebsiteMVC\AbstractController;
use EditoWebsiteMVC\ViewRender\CLI as CLIViewRender;
use EditoWebsiteMVC\ViewRender\HTMLTemplate as HTMLTemplateViewRender;
use Zend_XmlRpc_Server as XmlRpcServer;
class UIGatewayController extends AbstractController
{
public function xmlRpcAction()
{
$svr = new XmlRpcServer();
$svr->setClass('FrontGateway');
echo $svr->handle();
exit;
}
}
The code in the getEdito method from the DirectDbConnectionV2 is never reached.
Is there something I need to enable on the server ? or a port that I need to open ?
EDIT EDIT
I should mention that the code is working on another server that I've access to, is there anything I should compare / check to maybe solve that issue ?
Thanks a lot
I don't think there's enough info to even make a guess, but let me try.
I've faced similar issue, where requests sent never reached the server. It turned out to be that Zend_Http_Client_Adapter_Socket adapter is binding to an IPv6 and due to routing issues request never got to the server.
In the end, what solved the issue was:
$client->getAdapter()->setStreamContext(array(
'socket' => array('bindto' => '0:0'),
));
where $client is an instance of Zend_Http_Client.
Again, it's just a shot in the dark, but could be worth trying. :)
Edit:
In your case, you should add following to FrontService constructor:
$this->client->getHttpClient()->getAdapter()->setStreamContext(array(
'socket' => array('bindto' => '0:0'),
));
Edit Edit:
Since back on 1.9.0 there's no getAdapter on Zend_Http_Client, you have to create adapter yourself and pass it to http client:
public function __construct($xmlRpc)
{
$this->client = new Zend_XmlRpc_Client($xmlRpc);
$adapter = Zend_Http_Client_Adapter_Socket();
$adapter->setStreamContext(array(
'socket' => array('bindto' => '0:0'),
));
$this->client->getHttpClient()->setAdapter($adapter);
}
Cheers.

Phalcon : How to access global function?

I am totally new to use phalcon.
1. I have created a directory by name library
2. In that directory i have created a file by name commonfunctions.php
3. and i written a
abstract class Commonfunctions extends Phalcon\Mvc\User\Component
{
Public function ProfileImage() //function to set profile pic
{
$auth = $this->session->get('auth');
$user_id = $auth['id']; //get session id
$TblPersonaldetails = TblPersonaldetails::findFirst("user_id = ".$user_id);
echo "pic = ".$profile_pic = $TblPersonaldetails->profile_pic; //get profil_pic path from db
}
}
but I am getting notice message from "Notice: Access to undefined property TblPersonaldetails::profile_pic in D:\xampp\htdocs\test\app\library\Commonfunctions.php on line 98"
How can I resolve this?
This might be what you are looking for.
Service create a folder called Service, Then move your Commonfunctions into the neewly created Service folder. Inside your Commonfunctions file added the namespace *Service*
In your config.php or loader.php do something like
$loader->registerNamespaces(
array(
"Service" => $config->application->servicesDir,
)
);
Your config should have the servicesDir set to something like app/services
Then if that all loads succsefully you can call your method "ProfileImage" like so
$app->getDI()->get('Service\Commonfunctions')
I hope this helps

Is there zend bootstrap analog in yii?

I want to try db connection to check is db available. In zend I can place my code in boostrap file and wrap it in try catch.
How to implement this in yii?
Is in yii analog of zend boostrap?
UPD: db is mongo, yii extention for working with db is a directmongosuite
Seems that I find appropriate solution:
Need to prohibit auto connect in config file:
'components' => array(
'edms' => array(
'class' => 'EDMSConnection',
'dbName' => 'homeweb',
'server' => 'mongodb://localhost:27017',
'options' => array('connect' => false)
)
)
all controllers should extend one custom controller (BaseController for example).
Need to write own public function beforeAction method where I can add boostrap code.
class BaseController extends CController
{
public $layout = '//layouts/main';
public $navigationMenu = array();
public $breadcrumbs = array();
public function beforeAction($action)
{
try {
Yii::app()->edmsMongo()->connect();
} catch (Exception $e) {
die('Cannot connect to the database server. Please Try again later.');
}
$isGuest = Yii::app()->user->isGuest;
$this->navigationMenu = $this->_getNavigationMenu($isGuest);
return parent::beforeAction($action);
}
In the beforeAction method need to add return true or execute parent's method.
The bootstrap in yii is pretty much the index.php file under public_html or the yiic.php file (for command line applications).
You will probably have to separate the creating of the application instance and running it (by default it does both on 1 line), so you can do your try/catch between the calls.
Just try to fetch the app component, the mongo plugin will throw an exception if it can't open the connection:
try
{
Yii::app()->mongoDb;
}
...
or Yii::app()->getComponent('mongoDb');

Proper way to use a config file?

I just started using a PHP framework, Kohana (V2.3.4) and I am trying to set up a config file for each of my controllers.
I never used a framework before, so obviously Kohana is new to me. I was wondering how I should set up my controllers to read my config file.
For example, I have an article controller and a config file for that controller. I have 3 ways of loading config settings
// config/article.php
$config = array(
'display_limit' => 25, // limit of articles to list
'comment_display_limit' => 20, // limit of comments to list for each article
// other things
);
Should I
A) Load everything into an array of settings
// set a config array
class article_controller extends controller{
public $config = array();
function __construct(){
$this->config = Kohana::config('article');
}
}
B) Load and set each setting as its own property
// set each config as a property
class article_controller extends controller{
public $display_limit;
public $comment_display_limit;
function __construct(){
$config = Kohana::config('article');
foreach ($config as $key => $value){
$this->$key = $value;
}
}
}
C) Load each setting only when needed
// load config settings only when needed
class article_controller extends controller{
function __construct(){}
// list all articles
function show_all(){
$display_limit = Kohana::config('article.display_limit');
}
// list article, with all comments
function show($id = 0){
$comment_display)limit = Kohana::config('article.comment_display_limit');
}
}
Note: Kohana::config() returns an array of items.
Thanks
If you are reading a group of configuration items for a controller, store them in class member ($this->config), if you are reading a single configuration item; read it individually.
I think first method (A) should be fine, it has lesser code and serves the purpose fine.
If you have site wide stuff that you want access to from "anywhere", another way of doing it may be to put something like:
Kohana::$config->attach(new Kohana_Config_File('global'));
in bootstrap.php. Then create global.php in the application/config directory with something like:
return (array ('MyFirstVar' => 'Is One',
'MySecondVar' => 'Is Two'));
And then when you need it from your code:
Kohana::config ('global.MyFirstVar');
But I suppose all of this comes down to where and how you want to use it.

Categories