Customize logging - CakePHP (1.3) - php

I would like to extend the cakephp logging facility.
Using
$this->log($msg, $level)
you can log a $msg with $level to tmp/logs/$level.log.
How I would like to use logging is:
Separate functions for different levels, e.g. $this->debug($msg) for $this->log($msg, 'debug') and $this->error($msg) for $this->log($msg, 'error') etc. for logging.
Automatically put the name of the class in front of a message, e.g. $this->debug($msg) will lead to "MyClass: $msg" if $this is of type "MyClass".
I know I can extend the functionality by extending AppModel, AppController etc., but as I need the functionality everywhere in my application, I would rather need to extend cakephp's Object - but didn't find a stable mechanism for that (don't want to change it in the cake/ folder).
I though about implementing a new class for that functionality, but I'm not sure how to make that available in cakephp.
Could you please give me some hints where/how I can implement these extensions neatly?

Global convenience methods
Well, you can't really do monkey patching in PHP (5.2 at least), and that is probably a good thing for the the developers that have to maintain your code after you are gone. :)
CakePHP - being an MVC framework with strict conventions - makes it hard for you to break the MVC paradigm by only allowing you the extend the parts you need in isolation (ie. AppModel, AppController, etc.) and keeping the object-orientated foundation untouched in the core (making it hard to add code that "can be used everywhere" for potential misuse).
As for adding functionality that transcends all the MVC separation, the place for this is app/config/bootstrap.php. When you place code here it seems clear that it is not part of the framework (quite rightly so), but allows you to add these sort of essentials before CakePHP even loads. A few options of what to do here might be:
Create a function (eg. some custom functions such as error() that call CakeLog::write() in the way you like.)
Load a class (eg. load your very own logging class called something like.. Log, so you can call Log::error() in places)
See below:
The logger API
Cake does allow for many customisations to be made to things like the logger, but unfortunately the API exposed to us is already defined in the core in this case. The API for logging in CakePHP is as follows, and you can use either approach anywhere you like (well, the former only in classes):
$this->log($msg, $level) // any class extending `Object` inherits this
// or
CakeLog::write($level, $message); // this is actually what is called by the above
The arbitrary $level parameter that you are trying to eliminate is actually quite a powerful feature:
$this->log('Cannot connect to SMTP server', 'email'); // logs to app/logs/email.log
// vs
$this->email('Cannot connect to SMTP server'); // ambiguous - does this send emails?
We just created a brand new log type without writing an extra line of code and it's quite clear what the intention of our code is.
Customising the logger
The core developers had the foresight to add a condition allowing us to completely replace the logger class should we wish to:
function log($msg, $type = LOG_ERROR) {
if (!class_exists('CakeLog')) { // winning
require LIBS . 'cake_log.php';
}
// ...
As you can see, the core CakeLog class only gets instantiated if no such class exists, giving you the opportunity to insert something of your own creation (or an exact copy with a few tweaks - though you would want to sync changes with core - manually - when upgrading):
// app/config/bootstrap.php
App::import('Lib', 'CakeLog'); // copy cake/libs/cake_log.php to app/lib/cake_log.php
The above would give you full control over the implementation of the CakeLog class in your application, so you could do something like dynamically adding the calling class name to your log messages. However, a more direct way of doing that (and other types of logging - such as to a database) would be to create a custom log stream:
CakeLog::config('file', array(
'engine' => 'FileLog', // copy cake/libs/log/file_log.php to app/libs/log/file_log.php
));
TL;DR - Although you can load your own code before CakePHP bootstraps or for use in isolation in each of the MVC layers provided, you shouldn't tamper with the object hierarchy provided by the core. This makes it hard to add class methods that are inherited globally.
My advice: use the API given to you and concentrate on adding more features instead of syntactical subtleties. :)

In addition to what deizel said (great writeup, by the way, deizel), you don't have to use Cake's logger. You're welcome to use any logging system you'd like. Choosing an existing logging framework that you like would probably be the safest bet. bootstrap.php is a good place to do any require calls or initializations.
Otherwise, if you'd like to do things 'in' Cake, I'd recommend creating a plugin with a trio of logging interfaces: a Component, a Behavior, and a Helper. That way the logging functionality would be available in your models, views, and controllers. As for how to code it, I like the idea making the cake classes thin proxies to your real logging class, and using the magic method __call() in your proxies to parse logging requests and environment, then forward on that information to your logger to handle uniformly.
You'd be able to write things like $this->MyLogger->oops("stubbed my toe") and potentially have an oops.log file with your messages and whatever additional information (calling controller/view/model, time&date, etc.) you'd like included.

Related

PHP: How to control multiple instances of Class in MVC (where multiple modules load) without Singleton

I am creating a very basic application framework for my project that uses the standard MVC approach and has support for modules (which I'm calling apps). There are a number of global objects created like $URI, $ROUTER, $PROFILE, etc. and access to global libraries like Array Helpers and Calendar generators. All of it is similar to Codeigniter or FuelPHP and any number of other frameworks, but we wanted something specific to our needs and decided to go from scratch (borrowing and modifying some libraries from the above).
My question is this. If one module loads the Calendar library, and the Calendar Library has no need for constructor variables or dependencies (i.e. every new \Calendar) will be identical), is there a way to ensure that only one calendar object is created? So if Module 2 tries to create a Calender Object that Module 1 has already created, the system would deliver the same object. I should clarify that multiple modules can run at once (why we needed a new framework).
I've heard terrible things about singletons and haven't been impressed with factories (which I may not be using correctly).
What is best practice?
Thanks!
How about an inversion of control system? You could make a global IOC object that has instructions for creating an object, but that also has a registry that contains references to already created objects. In the registration portion of the module for each item that you want to behave "singletonny", you simply check to see if it's already been instantiated.
The only other option I can think of is that since you aren't looking to construct anything, make it a static class that you can't instantiate and access the class statically (Calendar::printSomeFunction).
I am not, however, opposed to the singleton pattern, for what it's worth, when it's used correctly. I just choose more elegant solutions such as #1 here, because it is very flexible. You don't however have much control over whether or not a dev creates a class outside of the IOC module so you might consider protecting that in some way.
Hope that helps your decision making process.
What if you used a session flag?
if(!$_SESSION['calender']){
$calander = new Calander();
$_SESSION['calender'] = true;
}
Would this work for you?
What you'll want is something like a service container. Like:
$server_container->add_service("my calendar", "Calendar");
Then any module that needs a calender (or "my calendar" in specific) can be constructed with:
$mymodule = new MyModule($service_container->get_service("my calendar"));
class MyModule {
public function __construct(Calendar $calendar) { /*..*/ }
}
Singletons are bad because it makes your code untestable. With code like the above you can replace $calendar by a stub that implements Calendar. Proper DI would argue that you need a CalendarInterface too but you might have dependencies that don't allow you to make that distinction.

CodeIgniter (pre-controller) hooks and caching

Summary:
Do pre-controller hooks execute during caching? Is there any hook-point which will execute? (pre-system?)
I should probably highlight the fact that the hook doesn't affect the content that is sent to the browser. That isn't an issue.
Detailed version:
I plan on implementing some statistics-type functionality in a project I've built using PHP and CodeIgniter.
The project in question is a custom built CMS - due to the extended intervals between updates I've used caching to help speed up load times; this isn't essential but it's preferential. It seems to be a good solution to a largely static site; especially where dynamic content is primarily served client-side - i.e AJAX requests.
The proposed functionality primarily involves a pre-controller hook which accesses methods through libraries such as the User Agent library, before dumping them to a database. From here it can be polled, outputted via JSON and manipulated before being displayed by something like the jQuery flot plugin.
I've read through the documentation on the Web Page Caching as well as the documentation regarding hooks. Unfortunately, it's still not clear whether using caching will completely bypass the hooks.
I'm aware of the cache_override however this means implementing your own caching mechanism; not what I want to do!
The alternative would be gathering statistics client side and submitting it to the server via AJAX; but this isn't ideal either as I'm trying to have a clear separation of logic - for maintenance and testing reasons.
In short:
Do pre-controller hooks execute during caching? No.
Is there any hook-point which will execute? Yes pre_system does execute.
If caching kicks at system/core/CodeIgniter.php:189, the only hook that gets a chance to run is pre_system (system/core/CodeIgniter:124).
Unfortunately you don't get much functionality of codeigniter at that point, no get_instance() and without that most core libraries are not loaded as well. If you are inclined you can look into what functions are defined inside system/core/Common.php thats pretty much all you got.
If you are really want to make this work with the built in classes you can sort of fight your way to a database object and other core stuff like this:
You will have to manually get the BASEPATH.'database/DB.php' file included in. Fortunately in the loader class, it loaded with require_once so it won't break the page on cache miss.
Once you got the Database library loaded instantiate the usual $this->db object with calling DB(). Without parameters it will load the default database from the config files as usual.
At this point you can write your queries from your pre_system hook, and since hooks can be objects, you can move every logging code inside the hook's object. If you need other libraries you can get an instance of them with the load_class() function (don't forget to set the third prefix parameter to empty string if you are not loading a built in class).
At the end you should end up like this (imaginary code):
class MyLoggingHook {
// called from the hook config
public function run($params = array()) {
require_once(BASEPATH.'database/DB.php');
$db = DB(); // getting hold of a DAO instance
// routing information is always useful to have for pageview logs
$RTR = load_class('Router', 'core');
$RTR->_set_routing();
// Router also load Uri and Config classes inside so the following two instances could be interesting too:
// $RTR->uri
// $RTR->config
// load some useful library not related to CodeIgniter
$user_agent_detector = load_class('UserAgentDetector', 'libraries', '');
// do some logging
$db->insert('page_view_log', array('class' => $RTR->fetch_class(), 'method' => $RTR->fetch_method(), /*...*/);
}
}
I should probably mention that i've never used something like this in production and there's the risk of relaying on funcionality that could change from version to version. If you can do without touching the Codeigniter classes inside your hook go with that.
Using PDO for database access, loading the database config with get_config(), you can get by without touching any codeigniter related classes.

What are some PHP object-oriented framework initialization techniques?

I have an object oriented framework that uses a page design, where each page extends a view of the framework. So, for instance, my index page for a site is actually a class that implements the abstract class View provided by the framework. I hook the framework by including a startup script at the top of the page and after some processing the framework creates an instance of the page and processes its view data. To add flexibility to the system, I don't require the class name to be the name of the file itself. This allows me to create something like a support class and have it behave as the index for the /support/ subdomain.
I was initially passing the page's class name into the framework via the framework's constructor, but this added a few more steps to the top or bottom of the page. I currently obtain the class name via a pages table in the database identified by a filtered requested URI. I use this table to build navigation and adding an extra table column was practically free. This works OK as long as I have a database connection, but I'm trying to implement static page support for status messages and error reporting, and I need another method for creating an instance of the page's class. If I use the standard convention of naming the class the file's name, then I know I have a dependable way of extrapolating the class name. I don't really want to name all my classes index just for presentation reasons. What is some advice or some standards for how object oriented frameworks are initialized?
View.inc
<?php
abstract class View
{
abstract function getView();
}
?>
Startup.inc
<?php
require_once("View.inc");
require_once("CoreController.inc");
$Framework = new CoreController();
$Framework->Initialize();
exit;
?>
index.php
<?php
require_once("Startup.inc");
class Index extends View
{
public function getView()
{
echo "<pre>View Data</pre>";
}
}
?>
Within my framework I have a TemplateController that processes the page. The page class is known because it is mapped via another class. Without a database however, I would like to discover the class within, say, index.php without changing the way it's currently set up. Here is the actual code within the TemplateController.
//Get the View Class from Page
$view = $page->getPageClass();
//We need to catch View creation failure
$this->Page = new $view($this->Framework);
//Initialize the Page View
$this->Page->Initialize();
//Cache the Page View
$this->cacheView($this->Page, $page->getPageName(), $this->SiteID.TCS_PAGE_SORTID);
In the snippet above $view is the actual name of the class that was mapped from another controller. I'm passing a reference to the framework to the view's constructor and the rest is really irrelevant. I'm trying to come up with a similar mapping technique to identify the page class in the event the database is down. I like the one include line for the framework startup and would like to keep it that simple.
At the top of the TemplateController I have to also reinclude the actual page, since my startup script is at the top, the actual class is not included even though it is the requested page.
include($_SERVER['SCRIPT_FILENAME']);
Please review Stack Overflow question Identifying class names from $_SERVER['SCRIPT_FILENAME'] for more information on what I'm attempting to do.
Here is my checklist of page routing:
Adding new page must be quick
You must not be able to add page unintentionally
Application with million pages should not be slower or more bloated than application with 2 pages
Provide simple way and let people enhance it if they want
Allow easy re-factoring, such as moving several pages into different location
Make framework detect everything. Don't force user to specify base URL, etc.
Create simple to understand page names (hello/world).
Clean illegal characters from the URL
Make it possible to add static pages easy
Provide a way to generate URLs from page names.
Allow user to use pretty URLs by changing what appears before and after the page in the URL
And most importantly
- Stop copying, think about the best approach.
All of those suggestions I have used in the PHP UI framework - Agile Toolkit where I am a contributor.
Relevant sources: Agile Toolkit - a PHP Framework with jQuery, Agile Toolkit - PageManager.php, Agile Toolkit - URL.php and Agile Toolkit - PathFinder.php.
We wanted to make it really simple for developers. And secure too. And flexible. Therefore the "page" class is selected based on the URL. How? Quite easy:
/hello.html -> page_hello
/hello/world.html -> page_hello_world
Class then is mapped into filename. page/hello/world.php
Then there are cases when we want to use dynamic URLs too, such as: /article/234
Many frameworks implement a complex techniques here (arrays, regular expressions, front-controllers). We don't. There is mod_rewrite for this. Just rewrite this into page=article&id=234 and it works. And scales.
Apart from pages, there are other classes, but those classes can't be accessed directly. Therefore pages live under the /page/ folder, do distinguish them and maintain security.
Then comes the designer saying - "I won't write PHP". So we introduce static pages. If class page_hello_world is not defined, we'll look into template/skin/page/hello/world.html. That's a easy shortcut for designers and non-developers to add a new page.
What if a page is not found? Api->pageNotFound() is called. Feel free to redefine and load pages from SQL or display 404 page with a picture of a pink elephant.
And then there are some pages which come from add-ons. We don't want to enable them by default, but instead let users add them to their app somewhere. How?
class page_hello_world extends Page_MegaPage
Next question, is how we handle sub-pages of that page, since sometimes all the functionality can't fit on single page. Well, let's add support for page_edit() method (or any page_XX) as an alias for a sub-page inside those classes. Now add-on developer can include a multifunctional page which can be extended, customized and placed anywhere in the application.
Finally there are hackers, who want to do something really fast. For them we apply same technique to the API. You can define function page_hello_world in the API, and you don't need class.
Some might say that there are too many ways to do a simple thing. Oh well.
I hope that this was helpful.
Use __autoload(). Most major PHP frameworks use autoloading to streamline class loading.
You need some way to map a URL to an object, which is usually handled by a routing component in most frameworks. Might want to take a look at libraries such as https://github.com/chriso/klein.php, or the routing components of the major Frameworks out there (Zend, Symfony, etc.).
Why not to use information from URL to detect correct class? Since you won't use database for static pages, you have to somehow store mapping between URL and class in file. I.e. you will have a file mapping.php:
return array(
'about' => 'AboutView',
'copyright' => 'CopyrightView',
);
Here, about and copyright are URL components and values represent appropriate child classes of View. You can have URL's like http://example.com/index.php?page=about and use rewriting capabilities of webserver to make them look good.
You will change implementation of Page::getPageClass() in order to return correct view class. Depending on URL it will use static mappings from the file above or use database.
What's the problem with this approach?

PHP OOP - How to handle authorisation?

I'm building a management system for an idea I have. I'm well versed in PHP (at least enough to do everything I need to do) but I'm not that experienced with using OOP. I use it as much as I can but a lot of the best practices I'm not familiar with so when I do things I worry I'm doing them in the wrong order.
For this project I have a class for the thing the user is managing, I need to check whether or not the user has permissions to manage it. I know how to check the permissions, my question is: where should I be doing it?
Should I be doing it outside the class, like so:
if user permissions are valid
initialize class
else return error
or should I be doing
initialize class
class checks permissions
class returns error if permissions are invalid
I'm unsure which is the correct approach. On the one hand checking within the class seems the best based on what I know of OOP methodology, but then I also have the feeling that letting it get as far as initializing the class when permissions are unknown might be bad.
How should I be doing it? If there's any sort of article that covers this sort of thing a link would be greatly appreciated (I can't find anything through searches but I'm not 100% sure if I'm searching for the right thing as I know little of OOP)
It depends on what is your permissions model, and there is no "one correct way" to do it. It's a matter of approach. The important thing, is that whatever you choose, you use it consistently.
In my latest projects, I came across several different models. One of the most straightforward is a page-based permission, which is good if you do page-based flow, and use objects for support: you define at the top of the page who is supposed to access it and in case you can redirect. This is the simplest one, but can be very useful on specific applications.
If you, on the contrary, use objects to do your main flow, you should secure your object methods (rather than class instantiation). If you have a "save()" method, which can be called by specific users only, first thing when you enter that method, do your permissions check.
I am currently using an MVC pattern, and I have a Controller, which dispatches the actions to its children. Its only public method is execAction($params) and it will call actionAction($params) on itself, but first it will check permissions.
One important thing to remember is: never present actions on the UI that the user is not allowed to do (unless you are trying to force him to buy your "PRO version", that is) ;-)
I have written a pretty solid and robust CMS system. Here's how I do it and I hope you can extrapolate some information on making your own solution.
I have an index file, which loads an Admin class. Functionality in my CMS is modular (so containing in its own file and class).
A module is loaded based on a $_GET parameter.
Because the function to check the $_GET parameter and load the corresponding function is in my Admin class ($admin->pick_method()) and I also have a User object in my Admin class, I can first check the requested module is in the currently logged in user's permissions array.
If the permissions check returns true, I load the module. If false, I display a friendly "unauthorized access" page.
Hope this helps.
I think best way to do is to have class of permissions.
And then you can check before creating object or in object.
create permission class
if access then create class and set permission object
else error
// do action
if have permissions show something
else do not show something
Look how done in zend acl component
Validating within the class generates a dependency between the class and the permissions authorisation which isn't good because you are tying together two potential disparate items. You can solve this by Inversion of Control (eg. dependency injection) or as I do by authorisation notifications using Emesary.
Validating outside of the class is possibly worse because there is a real danger that the authorisation check will be wrong or missed completely. It also creates the wrong sort of linking between objects as the object is not in control of itself.
If you are going to do it outside of the object when it is created then it is probably better to require the object to provide an interface such as IAuthorisable which can be verified by a seperate object.
e.g.
interface IAuthorisable
{
public function getRequirements();
}
class Authorisation
{
public static createObject($newObj)
{
if ( canDo( $newObj->getRequirements()) )
return $newObj;
return null;
}
}
class Something implements IAuthorisable
{
public function getRequirements()
{
return SomeSortOfIdentifierOrSomething;
}
}
$mySomething = Authorisation::createObject(new Something($p1, $p2), "
If $mySomething is null it isn't allowed. Obviously this needs extending and designing properly which is left as an exercise for the reader.
OO basics
If it makes sense to include it in the class. You could do it.
Does a Book class have an authenticate function? No, functions like download() and convertToPDF() make more sense.
My approach
I always try to find the route of the least resistance.
If there are 10 scripts/pages that talk to 1 class and 1 or 2 scripts needs authentication for certain actions i would build the authentication into those 1 or 2 scripts. (or put them in a subfolder with a .htpasswd)
But when you're using a MVC structure, everything is a class, so its become a question of deciding which class.
I tend to put the authentication rules in the Controllers classes and the authentication to database-logic in a User class.

What are some good ways to write PHP application with modules support?

I'm starting to write a application in php with one of my friends and was wondering, if you have any advice on how to implement module support into our application.
Or is there a way how to automatically load modules written in php by a php application? Or should i just rely on __autoload function?
And we don't need plugins that are installable via a web interface, we just need some clever way to associate web pages of our project to some classes (they will render the page) so index.php can call the right class and retrieve it's generated sub-page.
And we are not using any kind of framework, for now at least.
Re your comment: Autoloading in conjunction with strict file naming would be totally enough in this case IMO.
You could define a specific namespace (not in the new PHP 5.3 namespace way, just in the sense of a common prefix to names), e.g. Module_* for module class names.
You could then organize your modules in directories with class files that contain exactly one class definition, for example:
/modules/Mail/index.php // defines class Module_Mail
/modules/Database/index.php // defines class Module_Database
/modules/Image/index.php // defines class Module_Image
Your autoloader function would then, whenever a Module_* class is requested:
$Database = new Module_Database("localhost", .....);
include the correct file from the right directory.
That's the way e.g. the Zend Framework does it, and does so pretty well.
Consider choosing a more specific namespace than Module_ to assure interoperability with other scripts and applications if that is an option in the future.
Slightly related: In a PHP project, how do you organize and access your helper objects?
It sounds like you are looking for a way to organise the different tasks that each page needs to carry out. In this case, take a look at the MVC pattern. It provides a simple way to seperate your data access (models) and how you render/present information (views).
You can map pages to functions with ease. If you store the information in an array of mapped values, and then use a function to compare the requested URL with each of the URLs in the array. Such an array could look like this:
$urls = array(
'/' => 'index',
'/aboutus/' => 'aboutUs',
);
There are several articles that discuss how to implement it in PHP in a couple of hours. This article is a very simple guide. I am not a fan of their use of the registry pattern but reading through should provide you with enough information as to how you can implement it yourself.
Regarding autoloading, you can also use spl_autoload_register, to define several (more than one) autoload functions, so each module can set up it's own implementation of autoloading.
All you need here is an MVC architecture, with one Controller class associated with each "module".
If you are not against using a framework, go for Zend MVC
It allows you to have the following principle :
An URL like this : http://yoursite.com/my-module/edit
Will more or less automatically call the editAction method in the MyModuleController class.

Categories