最喜欢的 Kohana 技巧和技巧特征?

发布于 2024-08-23 21:25:19 字数 150 浏览 13 评论 0原文

受到其他社区 wiki 的启发,我有兴趣了解鲜为人知的 Kohana 提示、技巧和功能。

  • 请为每个答案仅提供一个提示。
  • 如有必要,添加 Kohana 版本。

这是一个社区维基

Inspired from the other community wikis, I'm interested in hearing about the lesser known Kohana tips, tricks and features.

  • Please, include only one tip per answer.
  • Add Kohana versions if necessary.

This is a community wiki.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

爱殇璃 2024-08-30 21:25:19

从数据库结果生成 Form::select() 选项

Kohana 3.1 和 3.0

$options = ORM::factory('model')
 ->order_by('title','ASC')
 ->find_all()
 ->as_array('id','title');

$select = Form::select('name', $options);

应该注意的是,这并不限于 ORM,可以用于所有数据库结果(它们都支持 as_array)。有关更多详细信息,请参阅数据库结果信息。

如果您想添加默认选项:

$options = Arr::merge(array('Please select a value.'), $options);

Generating Form::select() options from database result

Kohana 3.1 and 3.0

$options = ORM::factory('model')
 ->order_by('title','ASC')
 ->find_all()
 ->as_array('id','title');

$select = Form::select('name', $options);

It should be noted this is not restricted to the ORM and can be used on all database results (they all support as_array). See the database results information for more details.

If you want to add a default option:

$options = Arr::merge(array('Please select a value.'), $options);
£烟消云散 2024-08-30 21:25:19

显示最后执行的查询

Kohana 3.1 和 3.0

echo Database::instance()->last_query

取自 在 Kohana 3 中,如何找出查询期间发生的错误?

Show last query executed

Kohana 3.1 and 3.0

echo Database::instance()->last_query

Taken from In Kohana 3, how do you figure out errors made during a query?.

墟烟 2024-08-30 21:25:19

设置 Kohana::$environment

将这些行粘贴到您的 .htaccess 中:

SetEnvIf SERVER_ADDR "^(127\.0\.0\.1|::1)$" KOHANA_ENV=development
SetEnvIf SERVER_ADDR "^((?!127\.0\.0\.1|::1).)*$" KOHANA_ENV=production

现在,如果您在本地主机上,则处于开发模式,否则您处于生产模式

编辑:

Set Kohana::$environment

Paste these lines to your .htaccess:

SetEnvIf SERVER_ADDR "^(127\.0\.0\.1|::1)$" KOHANA_ENV=development
SetEnvIf SERVER_ADDR "^((?!127\.0\.0\.1|::1).)*$" KOHANA_ENV=production

now, if you're on localhost, you are in development mode, otherwise you're in production mode

Edit: Added support for IPv6

一片旧的回忆 2024-08-30 21:25:19

this->request->route->uri()this->request->uri() 之间的区别 (Kohana 3 )

// Current URI = welcome/test/5 
// Using default route ":controller/:action/:id"

// This returns "welcome/test/5"
echo $this->request->uri(); 

// This returns "welcome/test1/5"
echo $this->request->uri(array( 'action' => 'test1' )); 

// This returns "welcome/index"
echo $this->request->route->uri();

// This returns "welcome/test1"
echo $this->request->route->uri(array( 'action' => 'test1' ));

如您所见, $this->request->route->uri() 使用当前路由默认值(id 为 null),而 $this->request->uri() 适用当前 uri 段。

The difference between this->request->route->uri() and this->request->uri() (Kohana 3)

// Current URI = welcome/test/5 
// Using default route ":controller/:action/:id"

// This returns "welcome/test/5"
echo $this->request->uri(); 

// This returns "welcome/test1/5"
echo $this->request->uri(array( 'action' => 'test1' )); 

// This returns "welcome/index"
echo $this->request->route->uri();

// This returns "welcome/test1"
echo $this->request->route->uri(array( 'action' => 'test1' ));

As you can see, $this->request->route->uri() uses current route defaults (id is null), while $this->request->uri() applies current uri segments.

捎一片雪花 2024-08-30 21:25:19

使用 ORM 将数据添加到数据透视表

ORM add 函数接受第三个参数,您可以在其中指定要保存在 1pivot 表1 上的其他数据。

例如,如果一个用户有多个角色,一个角色有多个用户(通过名为 1roles_users1 的表),您可以通过将列键和数据值的数组作为第三个参数传递给 将信息保存到 1pivot 表1添加方法。

Kohana 3.1

不支持。另一种方法是加载数据透视表并添加数据,就像使用任何其他表一样。

Kohana 3.0

$user->add('role', $role, array('date_role_added' => time()));

其中 $roleORM::factory('role', array('name' => 'user'));

Add data to pivot tables using ORM

ORMs add function accepts a third parameter where you can specify additional data to be saved on the 1pivot table1.

For example, if a user has many roles and a role has many users (through a table named 1roles_users1), you can save information to the 1pivot table1 by passing an array of column keys and data values as the 3rd argument to the add method.

Kohana 3.1

Not supported. The alternative would be to load the pivot table and add the data as you would with any other table.

Kohana 3.0

$user->add('role', $role, array('date_role_added' => time()));

where $role is ORM::factory('role', array('name' => 'user'));

五里雾 2024-08-30 21:25:19

关闭 AJAX 请求的 auto_rendering

这些代码示例假设您从模板控制器进行扩展。

小哈纳 3.1

public function before()
{
    parent::before();

    if (Request::current()->is_ajax())
    {
      $this->auto_render = FALSE;
    }
}

小哈纳 3.0

public function before()
{
    parent::before();

    if (Request::$is_ajax)
    {
      $this->auto_render = FALSE;
    }
}

Turn off auto_rendering for AJAX requests

These code samples assume you're extending from the template controller.

Kohana 3.1

public function before()
{
    parent::before();

    if (Request::current()->is_ajax())
    {
      $this->auto_render = FALSE;
    }
}

Kohana 3.0

public function before()
{
    parent::before();

    if (Request::$is_ajax)
    {
      $this->auto_render = FALSE;
    }
}
总攻大人 2024-08-30 21:25:19

可维护的路由

与其在 HTML 和 PHP 中硬编码锚点位置,不如反向路由。这本质上意味着您定义路线位置,然后使用它们;如果您需要更改位置,只需在一个地方完成即可,而不是数百个。

路由可以在任何地方定义,但最好将它们放入应用程序引导程序或模块引导程序 (init.php) 中。

它们的设置如下:

Route::set('name', '<controller>(/<action>)', array('action' => 'login|logout');
  1. 路由名称
  2. 要匹配的 URL 路径。
  3. 用于限制 匹配内容的正则表达式。

当某个部分被括号包围时,该部分是可选的。如果用户未提供部件而您想要提供默认值,则使用 defaults 方法来指定值。

->defaults(array('action' => 'login'));

Kohana 3.1 和 3.0

以下代码现在用于具有可逆路线。 URL 路径可以更新,并且您的所有 URL应该像以前一样工作。

Route::url('name', array('controller' => 'user', 'action' => 'login'));

Maintainable routes

Instead of hardcoding anchor locations in your HTML and PHP, it's a good idea to reverse routing. This essentially means you define route locations and then use those; If you ever need to change the location it's done in one place and not hundreds.

Routes can be defined anywhere, but it's good practice to put them into the application bootstrap or your modules bootstrap (init.php).

They are set as follows:

Route::set('name', '<controller>(/<action>)', array('action' => 'login|logout');
  1. Route name
  2. The URL path to match against.
  3. A regular expression to limit what the <part> is matched against.

When a part is surrounded by brackets, that part is optional. If a user has not provided a part and you want to provide a default value, then use the defaults method to specify values.

->defaults(array('action' => 'login'));

Kohana 3.1 and 3.0

The following code is now used for having reversable routes. The URL path can be updated and all your URLs should work as before.

Route::url('name', array('controller' => 'user', 'action' => 'login'));
睡美人的小仙女 2024-08-30 21:25:19

自动设置 base_url

Kohana::init(array(
    // ...
    'base_url' => dirname($_SERVER['SCRIPT_NAME']),
    // ...
));

如果您的网站托管在 1&1,您应该使用:(

Kohana::init(array(
    // ...
    'base_url' => substr($_SERVER["SCRIPT_NAME"], 0, strpos($_SERVER["SCRIPT_NAME"], basename($_SERVER["SCRIPT_FILENAME"])));
    // ...
));

取自 Gallery3 配置文件 )

Set base_url automatically:

Kohana::init(array(
    // ...
    'base_url' => dirname($_SERVER['SCRIPT_NAME']),
    // ...
));

If your site is hosted at 1&1, you should use:

Kohana::init(array(
    // ...
    'base_url' => substr($_SERVER["SCRIPT_NAME"], 0, strpos($_SERVER["SCRIPT_NAME"], basename($_SERVER["SCRIPT_FILENAME"])));
    // ...
));

(taken from Gallery3 config file )

究竟谁懂我的在乎 2024-08-30 21:25:19

检查内部请求

这些称为子请求。查看 Sam de Freyssinets 文章:扩展 Web应用程序与 HMVC 以获得更深入的解释。请注意版本之间的初始与实例差异。

小哈纳 3.1

if (Request::initial() !== Request::current())
{
    print 'Internal called made with Request::factory';
}

小哈纳 3.0

if (Request::instance() !== Request::current())
{
    print 'Internal called made with Request::factory';
}

Checking for an internal request

These are known as sub-requests. Take a look at Sam de Freyssinets article: Scaling Web Applications with HMVC for a more indepth explanation. Notice the initial vs instance difference between versions.

Kohana 3.1

if (Request::initial() !== Request::current())
{
    print 'Internal called made with Request::factory';
}

Kohana 3.0

if (Request::instance() !== Request::current())
{
    print 'Internal called made with Request::factory';
}
椵侞 2024-08-30 21:25:19

HMVC + AJAX = is_remote()

该函数检查内部请求和 AJAX 请求。如果页面的某些部分最初使用 HMVC 技术加载,然后可以使用 AJAX 重新加载,这可能会很方便。
将它与一些基本控制器一起放置,您可以从中扩展所有适当的控制器(我称之为“基本控制器”):

public function is_remote()
{
    if ($this->request->is_initial())
    {
        if ($this->request->is_ajax())
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
    else
    {
        return TRUE;
    }
}

一种更短(等效)的编写方式:

public function is_remote()
{
    return ( ! $this->request->is_initial() || $this->request->is_ajax());
}

希望这会有所帮助。

HMVC + AJAX = is_remote()

This function checks both - the internal and AJAX requests. It might be handy if some parts of the page are initially loaded using HMVC technique, and can be then reloaded with AJAX.
Place it withing some base controller, from which you extend all your proper controllers (I call it 'base controller'):

public function is_remote()
{
    if ($this->request->is_initial())
    {
        if ($this->request->is_ajax())
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
    else
    {
        return TRUE;
    }
}

A shorter (equivalent) way of writing this:

public function is_remote()
{
    return ( ! $this->request->is_initial() || $this->request->is_ajax());
}

Hope this helps.

爱*していゐ 2024-08-30 21:25:19

显示错误页面

如果您需要显示错误页面,Kohana 已为其内置了例外。引发异常后,您可以创建自定义异常处理程序并显示 HTML 错误页面。您需要一个开关来显示开发中的真正错误。

Kohana 3.1

throw new HTTP_Exception_404('The article :article was not found', 
    array(':article' => $article->name));

第二个参数为您提供了一种替换错误消息中的字符串的方法。

Kohana 3.0

没有捆绑 HTTP 异常。您应该创建自己的异常并处理它们。 Kohana 有一个教程:Kohana - 自定义错误页面

Display an error page

If you need to display an error page, Kohana has built in exceptions for it. Once you've thrown an exception, you can create a custom exception handler and have a HTML error page shown. You'll want a switch to show the real error in development.

Kohana 3.1

throw new HTTP_Exception_404('The article :article was not found', 
    array(':article' => $article->name));

The 2nd argument provides a way for you to replace strings in the error message.

Kohana 3.0

Doesn't have HTTP exceptions bundled. You should create your own exceptions and handle them. Kohana has a tutorial for this: Kohana - Custom Error Pages

赠意 2024-08-30 21:25:19

使用准备好的语句执行诸如TRUNCATE mytable之类的SQL查询,将 null 作为第一个参数传递给 DB::query() 方法。当查询不适合任何 CRUD 操作时很有用。

To execute SQL query like TRUNCATE mytable with prepared statements, pass null as first param to DB::query() method. Useful, when query doesn't fit for any of CRUD operations.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文