在 Symfony 2.1 中自动加载一个类 [英] Autoloading a class in Symfony 2.1

查看:24
本文介绍了在 Symfony 2.1 中自动加载一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个 Symfony 1.2 项目移植到 Symfony 2.x.我目前正在运行最新的 2.1.0-dev 版本.

I'm porting a Symfony 1.2 project to Symfony 2.x. I'm currently running the latest 2.1.0-dev release.

在我的旧项目中,我有一个名为 Tools 的类,它具有一些简单的功能,例如将数组转换为字符串和从字符串生成 slug.我想在我的新项目中使用这个类,但我不清楚如何在包之外使用这个类.

From my old project I have a class called Tools which has some simple functions for things like munging arrays into strings and generating slugs from strings. I'd like to use this class in my new project but I'm unclear how to use this class outside of a bundle.

我在这里查看了各种建议更改 app/autoload.php 的答案,但我的 autoload.php 看起来与答案中的不同,也许这里在 2.0 和 2.1 之间发生了一些变化.

I've looked at various answers here which recommend changing app/autoload.php but my autoload.php looks different to the ones in the answers, maybe something has changed here between 2.0 and 2.1.

我想将我的类保留在我的 src 或 app 目录中,因为它们受源代码控制.我的供应商目录不是我使用 composer 来处理的.

I'd like to keep my class in my src or app directories as they're under source control. My vendors directory isn't as I'm using composer to take care of that.

如果有任何建议,我们将不胜感激.

Any advice would be appreciated here.

推荐答案

对于这种简单的情况,最快的解决方案是直接在 src 下创建一个文件夹(例如 Common)代码> 并将您的课程放入其中.

For a simple case like this the quickest solution is creating a folder (for example Common) directly under src and put your class in it.

src
  -- Common
    -- Tools.php

Tools.php 包含具有适当命名空间的类,例如

Tools.php contains your class with proper namespace, for example

<?php

namespace Common;

class Tools
{
    public static function slugify($string)
    {
        // ...
    }
}

在调用你的函数之前不要忘记use语句

Before calling your function do not forget the use statement

use Common\Tools;

// ...
Tools::slugify('my test string');

如果您按照上述正确的文件夹结构和命名空间将您的代码放在 src 下,它会在不触及 app/autoload.php 的情况下工作.

If you put your code under src following the proper folder structure and namespace as above, it will work without touching app/autoload.php.

这篇关于在 Symfony 2.1 中自动加载一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆