Zend_Log in application.ini - php

is there any example how to setup an instance of zend log from application.ini? I have only found an example for logging to an file, but i want to log into an SQLITE database table?
Zend Log resource

Good question. I can't find a way to instantiate the Zend_Log_Writer_Db from a bootstrap config. The writer class requires a Zend_Db_Adapter object. It doesn't accept a string.
The ZF project needs to develop this use case further. They don't even have any unit tests for Zend_Application_Resource_Log that include a Db writer.
The best I can suggest until then is that you Bootstrap class needs to customize the Log resource in an _initLog() method.
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initDb()
{
if ($this->hasPluginResource("db")) {
$r = $this->getPluginResource("db");
$db = $r->getDbAdapter();
Zend_Registry::set("db", $db);
}
}
protected function _initLog()
{
if ($this->hasPluginResource("log")) {
$r = $this->getPluginResource("log");
$log = $r->getLog();
$db = Zend_Registry::get("db");
$writer = new Zend_Log_Writer($db, "log", ...columnMap...);
$log->addWriter($writer);
Zend_Registry::set("log", $log);
}
}
}

Here in the manual: you can find an example how to write your log file into the database.Is that what you mean?

This should work - I will test fully later (not at my dev machine now)
Zend_Application_Resource_Log can setup an instance of a Zend_Log from application.ini
resources.log.writerName = "db"
resources.log.writerParams.db.adapter = "PDO_SQLITE"
resources.log.writerParams.db.dbname = APPLICATION_PATH "/../db/logdb.sqlite"
resources.log.writerParams.db.table = "log"

Since ZF 1.10alpha (at least), the following has been true.
// e.g. 1 - works
resources.log.firebug.writerName = "Firebug"
// e.g. 2 - fails
resources.log.writerName = "Firebug"
NOTE: the arbitrary array key 'firebug'. When the Zend_Log factory churns over the resource's log config, example 1 will be passed as an array to Zend_Log->addWriter() (triggering the _constructWriterFromConfig() method), whilst example 2 will simply pass a string (triggering an exception).
(I know this is old, and I'm using a Firebug logger example, but the same applies to all log writers)

Related

PHP How to get proper case class name

class Google_Model_SomeThing { ... }
$className = 'google_MODEL_something';
I can create instance of class base on $className. But what if I would like to get proper case class name from $className without creating instance?
I expect something like this:
echo func('google_MODEL_something'); // Google_Model_SomeThing
or
$className = 'google_MODEL_something';
echo $className::class; // Google_Model_SomeThing
Reflection is most likely a better option, but here is an alternative:
You could use get_declared_classes after calling class_exists($wrongCaseName) and find the class name in the array of declared classes.
Example:
$wrongCaseName = 'Some\classy\THIng';
class_exists($wrongCaseName); //so it gets autoloaded if not already done
$classes = get_declared_classes();
$map = array_combine(array_map('strtolower',$classes),$classes);
$proper = $map[strtolower($wrongCaseName)];
Performance
The reflection-based method, noted by l00k, is significantly faster, by about 3 times. I ran this version vs the reflection version on 500 different classes with randomly generated names & no code within them. The reflection-method took about 0.015 seconds to get the proper case for 500 classes, and my get_declared_classes method took about 0.050 seconds for 500 classes.
More details on my personal website. Tested on PHP 7.2.19 on my localhost server on my laptop.
I found code below working, but is it the simplest solution?
$className = 'google_MODEL_something';
$reflection = new ReflectionClass($className);
echo $reflection->getName(); // Google_Model_SomeThing
Well I would suggest to create an instance and then get the className using get_class().
$bar = new $classname();
$caseClassName = get_class($bar);

Alternatives to static methods in a framework PHP

Lately I have been trying to create my own PHP framework, just to learn from it (As we may look into some bigger and more robust framework for production). One design concept I currently have, is that most core classes mainly work on static functions within classes.
Now a few days ago, I've seen a few articles about "Static methods are death to testability". This concerned me as.. yeah.. my classes contain mostly static methods.. The main reason I was using static methods is that a lot of classes would never need more than one instance, and static methods are easy to approach in the global scope. Now I'm aware that static methods aren't actually the best way to do things, I'm looking for a better alternative.
Imagine the following code to get a config item:
$testcfg = Config::get("test"); // Gets config from "test"
echo $testcfg->foo; // Would output what "foo" contains ofcourse.
/*
* We cache the newly created instance of the "test" config,
* so if we need to use it again anywhere in the application,
* the Config::get() method simply returns that instance.
*/
This is an example of what I currently have. But according to some articles, this is bad.
Now, I could do this the way how, for example, CodeIgniter does this, using:
$testcfg = $this->config->get("test");
echo $testcfg->foo;
Personally, I find this harder to read. That's why I would prefer another way.
So in short, I guess I need a better approach to my classes. I would not want more than one instance to the config class, maintain readability and have easy access to the class. Any ideas?
Note that I'm looking for some best practice or something including a code sample, not some random ideas. Also, if I'm bound to a $this->class->method style pattern, then would I implement this efficiently?
In response to Sébastien Renauld's comments: here's an article on Dependency Injection (DI) and Inversion of Control (IoC) with some examples, and a few extra words on the Hollywood principle (quite important when working on a framework).
Saying your classes won't ever need more than a single instance doesn't mean that statics are a must. Far from it, actually. If you browse this site, and read through PHP questions that deal with the singleton "pattern", you'll soon find out why singletons are a bit of a no-no.
I won't go into the details, but testing and singletons don't mix. Dependency injection is definitely worth a closer look. I'll leave it at that for now.
To answer your question:
Your exaple (Config::get('test')) implies you have a static property in the Config class somewhere. Now if you've done this, as you say, to facilitate access to given data, imagine what a nightmare it would be to debug your code, if that value were to change somewhere... It's a static, so change it once, and it's changed everywhere. Finding out where it was changed might be harder than you anticipated. Even so, that's nothing compared to the issues someone who uses your code will have in the same situation.
And yet, the real problems will only start when that person using your code wants to test whatever it is he/she made: If you want to have access to an instance in a given object, that has been instantiated in some class, there are plenty of ways to do so (especially in a framework):
class Application
{//base class of your framework
private $defaulDB = null;
public $env = null;
public function __construct($env = 'test')
{
$this->env = $env;
}
private function connectDB(PDO $connection = null)
{
if ($connection === null)
{
$connection = new PDO();//you know the deal...
}
$this->defaultDB = $connection;
}
public function getDB(PDO $conn = null)
{//get connection
if ($this->defaultDB === null)
{
$this->connectDB($conn);
}
return $this->defaultDB;
}
public function registerController(MyConstroller $controller)
{//<== magic!
$controller->registerApplication($this);
return $this;
}
}
As you can see, the Application class has a method that passes the Application instance to your controller, or whatever part of your framework you want to grant access to scope of the Application class.
Note that I've declared the defaultDB property as a private property, so I'm using a getter. I can, if I wanted to, pass a connection to that getter. There's a lot more you can do with that connection, of course, but I can't be bothered writing a full framework to show you everything you can do here :).
Basically, all your controllers will extend the MyController class, which could be an abstract class that looks like this:
abstract class MyController
{
private $app = null;
protected $db = null;
public function __construct(Application $app = null)
{
if ($app !== null)
{
return $this->registerApplication($app);
}
}
public function registerApplication(Application $app)
{
$this->app = $app;
return $this;
}
public function getApplication()
{
return $this->app;
}
}
So in your code, you can easily do something along the lines of:
$controller = new MyController($this);//assuming the instance is created in the Application class
$controller = new MyController();
$controller->registerApplication($appInstance);
In both cases, you can get that single DB instance like so:
$controller->getApplication()->getDB();
You can test your framework with easily by passing a different DB connection to the getDB method, if the defaultDB property hasn't been set in this case. With some extra work you can register multiple DB connections at the same time and access those at will, too:
$controller->getApplication->getDB(new PDO());//pass test connection here...
This is, by no means, the full explanation, but I wanted to get this answer in quite quickly before you end up with a huge static (and thus useless) codebase.
In response to comments from OP:
On how I'd tackle the Config class. Honestly, I'd pretty much do the same thing as I'd do with the defaultDB property as shown above. But I'd probably allow for more targeted control on what class gets access to what part of the config:
class Application
{
private $config = null;
public function __construct($env = 'test', $config = null)
{//get default config path or use path passed as argument
$this->config = new Config(parse_ini_file($config));
}
public function registerController(MyController $controller)
{
$controller->setApplication($this);
}
public function registerDB(MyDB $wrapper, $connect = true)
{//assume MyDB is a wrapper class, that gets the connection data from the config
$wrapper->setConfig(new Config($this->config->getSection('DB')));
$this->defaultDB = $wrapper;
return $this;
}
}
class MyController
{
private $app = null;
public function getApplication()
{
return $this->app;
}
public function setApplication(Application $app)
{
$this->app = $app;
return $this;
}
//Optional:
public function getConfig()
{
return $this->app->getConfig();
}
public function getDB()
{
return $this->app->getDB();
}
}
Those last two methods aren't really required, you could just as well write something like:
$controller->getApplication()->getConfig();
Again, this snippet is all a bit messy and incomplete, but it does go to show you that you can "expose" certain properties of one class, by passing a reference to that class to another. Even if the properties are private, you can use getters to access them all the same. You can also use various register-methods to control what it is the registered object is allowed to see, as I've done with the DB-wrapper in my snippet. A DB class shouldn't deal with viewscripts and namespaces, or autoloaders. That's why I'm only registering the DB section of the config.
Basically, a lot of your main components will end up sharing a number of methods. In other words, they'll end up implementing a given interface. For each main component (assuming the classic MVC pattern), you'll have one abstract base-class, and an inheritance chain of 1 or 2 levels of child classes: Abstract Controller > DefaultController > ProjectSpecificController.
At the same time, all of these classes will probably expect another instance to be passed to them when constructed. Just look at the index.php of any ZendFW project:
$application = new Zend_Application(APPLICATION_ENV);
$application->bootstrap()->run();
That's all you can see, but inside the application, all other classes are being instantiated. That's why you can access neigh on everything from anywhere: all classes have been instantiated inside another class along these lines:
public function initController(Request $request)
{
$this->currentController = $request->getController();
$this->currentController = new $this->currentController($this);
return $this->currentController->init($request)
->{$request->getAction().'Action'}();
}
By passing $this to the constructor of a controller class, that class can use various getters and setters to get to whatever it needs... Look at the examples above, it could use getDB, or getConfig and use that data if that's what it needs.
That's how most frameworks I've tinkered or worked with function: The application is kicks into action and determines what needs to be done. That's the Hollywood-principle, or Inversion of Control: the Application is started, and the application determines what classes it needs when. In the link I provided I believe this is compared to a store creating its own customers: the store is built, and decides what it wants to sell. In order to sell it, it will create the clients it wants, and provide them with the means they need to purchase the goods...
And, before I forget: Yes, all this can be done without a single static variable, let alone function, coming into play. I've built my own framework, and I've never felt there was no other way than to "go static". I did use the Factory pattern at first, but ditched it pretty quickly.
IMHO, a good framework is modular: you should be able to use bits of it (like Symfony's components), without issues. Using the Factory pattern makes you assume too much. You assume class X will be available, which isn't a given.
Registering those classes that are available makes for far more portable components. Consider this:
class AssumeFactory
{
private $db = null;
public function getDB(PDO $db = null)
{
if ($db === null)
{
$config = Factory::getConfig();//assumes Config class
$db = new PDO($config->getDBString());
}
$this->db = $db;
return $this->db;
}
}
As opposed to:
class RegisteredApplication
{//assume this is registered to current Application
public function getDB(PDO $fallback = null, $setToApplication = false)
{
if ($this->getApplication()->getDB() === null)
{//defensive
if ($setToApplication === true && $fallback !== null)
{
$this->getApplication()->setDB($fallback);
return $fallback;//this is current connection
}
if ($fallback === null && $this->getApplication()->getConfig() !== null)
{//if DB is not set #app, check config:
$fallback = $this->getApplication()->getConfig()->getSection('DB');
$fallback = new PDO($fallback->connString, $fallback->user, $fallback->pass);
return $fallback;
}
throw new RuntimeException('No DB connection set #app, no fallback');
}
if ($setToApplication === true && $fallback !== null)
{
$this->getApplication()->setDB($fallback);
}
return $this->getApplication()->getDB();
}
}
Though the latter version is slightly more work to write, it's quite clear which of the two is the better bet. The first version just assumes too much, and doesn't allow for safety-nets. It's also quite dictatorial: suppose I've written a test, and I need the results to go to another DB. I therefore need to change the DB connection, for the entire application (user input, errors, stats... they're all likely to be stored in a DB).
For those two reasons alone, the second snippet is the better candidate: I can pass another DB connection, that overwrites the application default, or, if I don't want to do that, I can either use the default connection, or attempt to create the default connection. Store the connection I just made, or not... the choice is entirely mine. If nothing works, I just get a RuntimeException thrown at me, but that's not the point.
Magic methods would help you: see the examples about __get() and __set()
You should also take a look at namespaces: it may help you to get rid of some classes with static methods only.

Reuse MySQL connection PHP object inheritance

I'm writing a single PHP script to migrate topics from an old forums site to a new one.
The old forums site use database "old_forums"
Thew new forums site use database "new_forums"
MySQL user "forums" has all privileges to both databases (I'm using 1 single user for convenience but I would not have any problems using 2 different users if required)
I have both forum hosted on the the same host - localhost
The script I have the following structure
<?php
class Forum {
//constants
const HOST = "localhost";
const DB_USER = "forums";
const DB_PASS = "forums";
...
//properties e.g. topic title, topic content
}
class OldForum extends Forum {
const DB_NAME_OLD = "old_forums";
public static function exportTopics() {
//some code
}
}
class NewForum extends Forum {
const DB_NAME_NEW = "new_forums";
public static function importTopics() {
//some code
}
}
OldForum::exportTopics();
NewForum::importTopics();
?>
I understand that I'm mixing procedural & object-oriented programming PHP (OOPP) here.
I'm new to object-oriented PHP but (I have experience with Java so I'm very open to some guide to make this pure OOPP)
I would like to ultilise 1 single MySQL connection for both OldForum and NewForum class.
Where should I instantiate a mysqli object?
e.g. inside Forum class' constructor or have a new mysqli object as a property of class Forum
so that I would create a new Forum object to initiate a MySQL connection
$a_forum = new Forum();
The mysqli connection is easy enough to share between instances by creating it once in your bootstrap file and then passing it to instances that need it, e.g.
$mysqli = new mysqli(/* connection params */);
$someClassUsingMySqli = new SomeClassUsingMySqli($mysqli);
$anotherClassUsingMySqli= new AnotherClassUsingMySqli($mysqli);
That will effectively limit the connection to one and you dont need to resort to globals inside your objects. This is called Dependency Injection and should be your prefered way of assigning dependencies to objects. It makes dependencies explicit and easy to swap out and thus benefits change, testing and maintenance.
As for your Import and Export Task, I wonder why you are doing this in PHP at all. It's apparently the same database server, so you could just do it inside your MySql instance. If you want to do it with PHP, I'd probably do something like this:
class MigrateForum
{
private $dbConnector;
public function __construct(DBConnector $dbConnector)
{
$this->dbConnector = $dbConnector;
}
public function migrate()
{
// orchestrate the migration (consider transactions)
$this->exportOldForum();
$this->importNewForum();
}
private function exportOldForum()
{
// code to export old_database_name.table_name
}
private function importOldForum()
{
// code to import new_database_name.table_name
}
}
You could extract the Import and Export methods into their own Classes and then use some sort of Composite Command Pattern, but that really depends on how modular you need this to be.
Different approach would be to create some VIEW in the new_forums database pointing to the old_forum database. In this case, all the "views" could have, for example, "old_" prefix? Something similar to this:
CREATE VIEW old_tbl_name AS
SELECT *
FROM old_forum.tbl_name
In such situation, you only have one connection to one database.

Shanty_Mongo and Zend Framework 1.11

I'm playin' around with zend framework 1.11 and mongo. I've decided to use Shanty_Mongo as a library to easy couple Zend and Mongo, but I'm stuck in this exception:
Can not save documet. Document is not connected to a db and collection
This is the code in the controller:
public function indexAction()
{
try {
$guestbook = new Application_Model_Guestbook();
$guestbook->setComment('Commento di prova')
->setEmail('info#example.net')
->save();
$all_elements = Application_Model_Guestbook::all();
$this->view->entries = $all_elements;
} catch (Exception $exc) {
echo $exc->getMessage();
}
}
This is (part) of the model:
class Application_Model_Guestbook extends Shanty_Mongo_Document
{
protected static $_db = 'test';
protected static $_collection = 'user';
protected $_comment;
.....
Shanty is in my library folder, and in application.ini i've added it:
resources.view[] =
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
autoloaderNamespaces[] = "Shanty"
On Shanty-Mongo docs, it's reported that
"If you are connecting to localhost without any authentication then no need to worry about connections any further. Shanty Mongo will connect automatically on the first request if no connections have previously been added."
but this does not happen.. I really can't guess why.
Obviously, mongo is running, since if i use php Mongo() i can access it and perform insertions, etc...
I'm running the latest version of mongo, zend on php 5.3.6 on osx 10.6.8
Thanks!
Your model should be like this
class Application_Model_Guestbook extends Shanty_Mongo_Document
{
protected static $_db = 'test';
protected static $_collection = 'user';
protected static $_requirements = array('comment'=>'Required')
I think you may want to switch that autoloaderNamespaces[] = "Shanty" line to be:
autoloaderNamespaces[] = 'Shanty_Mongo'
Other than that it looks OK....
That's an odd error message. Notice it doesn't say "unable to connect to MongoDB" or similar. It says that this document isn't connected to a collection. It sounds like a configuration issue to me.
In other areas of your code are you able to connect to the database?
Read from the database?
Allesio,
the element that both you and Adam C have put on the autoloaderNamespaces array are not quite correct. Try the following:
autoloaderNamespaces[] = "Shanty_"
You only need to put the top-level prefix followed by an underscore. Please let me know if this doesn't resolve the situation. Also, I've not seen that error message before. For sure, if you have a local install of mongoDB running, you won't need to specify any authentication parameters.
If the collection doesn't exist, Shanty will create it and if the document doesn't exist, Shanty will create that as well.
What operating system are you using?
I had a number of troubles with the package in the Ubuntu repositories. However, adding the 10gen repository in to apt and installing the latest stable version helped me out. Though even that seems to crash periodically.
Try adding this to Bootstrap.php:
protected function _initMongoDB() {
$connection = new Shanty_Mongo_Connection('mongodb://localhost:27017');
Shanty_Mongo::addMaster($connection);
}

How to avoid using PHP global objects?

I'm currently creating blog system, which I hope to turn into a full CMS in the future.
There are two classes/objects that would be useful to have global access to (the mysqli database connection and a custom class which checks whether a user is logged in).
I am looking for a way to do this without using global objects, and if possible, not passing the objects to each function every time they are called.
You could make the objects Static, then you have access to them anywhere. Example:
myClass::myFunction();
That will work anywhere in the script. You might want to read up on static classes however, and possibly using a Singleton class to create a regular class inside of a static object that can be used anywhere.
Expanded
I think what you are trying to do is very similar to what I do with my DB class.
class myClass
{
static $class = false;
static function get_connection()
{
if(self::$class == false)
{
self::$class = new myClass;
}
return self::$class;
}
// Then create regular class functions.
}
What happens is after you get the connection, using $object = myClass::get_connection(), you will be able to do anything function regularly.
$object = myClass::get_connection();
$object->runClass();
Expanded
Once you do that static declarations, you just have to call get_connection and assign the return value to a variable. Then the rest of the functions can have the same behavior as a class you called with $class = new myClass (because that is what we did). All you are doing is storing the class variable inside a static class.
class myClass
{
static $class = false;
static function get_connection()
{
if(self::$class == false)
{
self::$class = new myClass;
}
return self::$class;
}
// Then create regular class functions.
public function is_logged_in()
{
// This will work
$this->test = "Hi";
echo $this->test;
}
}
$object = myClass::get_connection();
$object->is_logged_in();
You could pass the currently global objects into the constructor.
<?php
class Foo {
protected $m_db;
function __construct($a_db) {
$this->m_db = $a_db;
}
}
?>
I recently revamped my framework in preparation for the second version of our company's CMS. I undid a huge amount of the things I made static in order to replace them with normal objects. In so doing, I created a huge amount of flexibility that used to rely on me going through and hacking into core files. I now only use static constructs when the only alternative is global functions, which is only related to low-level core functionality.
I'm going to show a few lines of my bootstrap.php file (all of my requests get sent through that file, but you can achieve the same result by including it at the top of every file) to show you what I mean. This is an pretty hefty version of what you'd probably use in your situation, but hopefully the idea is helpful. (This is all slightly modified.)
//bootstrap.php
...
// CONSTRUCT APPLICATION
{
$Database = new Databases\Mysql(
Constant::get('DATABASE_HOST'),
Constant::get('DATABASE_USER'),
Constant::get('DATABASE_PASSWORD'),
Constant::get('DATABASE_SCHEMA')
);
$Registry = new Collections\Registry;
$Loader = new Loaders\Base;
$Debugger = new Debuggers\Dummy; // Debuggers\Console to log debugging info to JavaScript console
$Application = new Applications\Base($Database, $Registry, $Loader, $Debugger);
}
...
As you can see, I have all kind of options for creating my application object, which I can provided as an argument in the constructor to other objects to give them access to these "global" necessities.
The database object is self-explanatory. The registry object acts as a container for object I may want to access elsewhere in the application. The loader acts as a utility for loading other resources like template files. And the debugger is there to handle debug output.
I can, for example, change the database class that I instantiate and, voila I have a connection to a SQLite database. I can change the class of the debugger (as noted) and now all of my debug info will be logged to my JavaScript console.
Okay, now back to the issue. How do you give other objects access to all of this? You simply pass it in an argument to the constructor.
// still bootstrap.php
...
// DISPATCH APPLICATION
{
$Router = new Routers\Http($Application);
$Router->routeUri($_SERVER['REQUEST_URI']);
}
...
Not only that, but my Router (or whatever object I construct with it) is more flexible, too. Now I can just instantiate my application object differently, and my Router will behave differently accordingly.
Well, if you already have some object by which you refer to the blog system, you can compose these objects into that, so that they're $blog->db() and $blog->auth() or whatever.

Categories