所以我的代码大部分时间看起来像这样:
function SendMailsAction(){ $logger->log('Started sending mails.') ... ... ...Some Code... ... ... foreach ($mails as $mail){ try{ $logger->log('Trying to send') $mail->send() $logger->log('Mail sent successfully.') }catch(Exception $e){ $logger->log('Failed to send mail.') } } ... ... ...Some Code... ... ... $logger->log('Finished sending mails.') }
有时我甚至必须登录2个表,所以绝大多数记录代码加倍,函数开始变得复杂和漫长.
我使用Zend框架的Zend_Log进行日志记录,所以我的问题不是记录类本身,而是将日志记录代码与代码功能本身分离开来,并保持分离问题.
有些人提出了面向方面的编程(AOP),但不幸的是,对于我的客户来说,不幸的是,PHP的AOP是不可接受的,所以我正在寻找面向对象的解决方案或最佳实践.
注意:
Sometimes I even have to log in 2 tables,so most of the logging code is doubled and the functions start to get complicated and long.
会很久如果您的代码执行大量日志记录,则会很长时间,因为它将不得不记录,并且其记录的每一行操作将意味着代码中有一行.然而,在任何情况下,不应该复杂,因为日志记录是您可以做的最简单的事情之一.令我担心的是,你提到“有时我甚至要登录2张桌子”.在我的书中,一行,两张,五张,六千张或一千张表由一行进行.每个记录器的代码不会翻倍.如果您要复制一行,并将$log更改为$log2,则显然会出错(tm).
Some people suggested Aspect Oriented Programming (AOP),but unfortunately AOP for PHP isn’t acceptable for my costumer,so I’m looking for an Object Oriented solution or best practice.
很好,AOP.它有缺点;与debug_backtrace方法一样,性能很高.那么加上代码变得越来越“神奇”,因为当您查看代码本身时,它会执行不清楚的事情.这增加了调试应用程序的时间.
我的$0.02首先,不要重复你自己:每个动作一个日志条目应该是足够的.使用灵活的记录器,可以在运行时连接到某些类.根据“严重性”或“类型”,确定是否将消息实际记录在记录器中.总而言之,只是实现观察者模式:
<?PHP namespace Foo; class MailService { public function attach( Observes $observer ) { $this->observers[] = $observer; } public function notify( $message,$type = 'notice' ) { foreach( $this->observers as $observer ) { $observer->notify( $message,$type ); } } public function sendMail( ) { $this->notify( 'Started sending mails','debug' ); $mails = array( ); foreach( $mails as $mail ) { try { $this->notify( 'Trying to send','debug' ); $mail->send( ); $this->notify( 'Mail sent succesfully','debug' ); } catch( Exception $e ) { $this->notify( 'Failed to send mail','notice' ); } } $this->notify( 'Finished sending mail','debug' ); } } interface Observes { public function notify( $message,$type = 'notice' ); } abstract class Logger implements Observes { protected $types = array( 'debug' => 0,'notice' => 1,'warning' => 2,'error' => 3 ); protected function code( $type ) { return isset( $this->types[$type] ) ? $this->types[$type] : 0; } } class FileLogger extends Logger implements Observes { public function __construct( $filename ) { $this->filename = $filename; } /** * @todo replace the method body with a call to,say,file_put_contents. */ public function notify( $message,$type = 'notice' ) { if( $this->code( $type ) > $this->code( 'notice' ) ) { // only for warning and error. echo $message . "\n"; } } } class DebugLogger extends Logger implements Observes { public function notify( $message,$type = 'notice' ) { if( $this->code( $type ) === $this->code( 'debug' ) ) { // only show "debug" notices. echo $message . "\n"; } } } $service = new MailService( ); $service->attach( new FileLogger( 'yourlog.txt' ) ); $service->attach( new DebugLogger( ) ); $service->sendMail( );