在Yii中导入外部php文件

问题描述:

I've got some files using raw php (including config files) that's used for the automatic mailing stuff in my server.

Suppose inside this file I define a couple of constants (define(...)) and an array filled with database connection info, like user, host and so).

The website is done using Yii, so it also uses a config file.

These raw files can be placed anywhere (inside protected, outside, at the same level of index.php, whatever).

Now the problem comes that I've got a different configuration file (and different users/password for databases, and so) outside Yii, but I need to use it in some places inside Yii, too.

Is there a clear way to import these files to a controller? I've done it placing them inside extensions, but the raw functions didn't work from there.

我有一些文件使用原始php(包括配置文件),用于我服务器中的自动邮件 。 p>

假设在这个文件中我定义了几个常量(define(...))和一个填充了数据库连接信息的数组,比如用户,主机等等。 p >

网站使用Yii完成,因此它也使用配置文件。 p>

这些原始文件可放置在任何地方(受保护,外部,同一地方) index.php的等级,无论如何)。 p>

现在出现的问题是我在Yii外面有一个不同的配置文件(以及数据库的不同用户/密码等),但我 需要在Yii内的某些地方使用它。 p>

有没有一种明确的方法将这些文件导入控制器? strong>我已经完成了它们的放置 内部扩展,但原始功能从那里起作用。 p> div>

The best approach would be to see if you can put your custom code into class files and put those in the components directory or similar and convert your files to classes (if they aren't already). That way you can get at your data without a lot of mixing of code which is going to be hard to maintain.

Simple approach will be to place the files in extensions and add the path of the extensions to your yii configuration. Then make a controller and call methods from its actions. Lets consider an example of swiftmailer. Here is a custom controller you can use.

class mailerController extends Controller{

public function actions()
{
    return array(
         //can add other actions here
    );
}
    public function actionIndex(){

        echo "use mailer?e=<email>&m=<message>&sub=<subject> to send mail from the site to the email address";

    }


    public static function actionSendMail($e,$m,$sub){  

        $content = $m ; // can use a template and then assign to content 
        $SM = new SwiftMailer(); //the external method, should be present in include path
        // Get config
        $mailHost = Yii::app()->params['mailhost'];
        $mailPort = 25; // Optional
        $Transport = $SM->smtpTransport($mailHost, $mailPort);
        $Mailer = $SM->mailer($Transport);
        $Message = $SM
            ->newMessage($sub)
            ->setFrom(Yii::app()->params['sitemail'])
            ->setTo($e)
            ->addPart($content, 'text/html');
        return ( $Mailer->send($Message));
    } }

once your controller is ready, it can be called like

yoursite.com/mailer?e=<email>&m=<message>&sub=<subject>