Difference Between view() and fetch() Methods in ThinkPHP5 Controllers

The article explains the distinctions between the view() helper and the fetch() method in ThinkPHP5 controllers, showing code examples for both inherited and non‑inherited controllers, discussing how they handle common template configurations, and recommending the preferred usage in projects.

php Courses
php Courses
php Courses
Difference Between view() and fetch() Methods in ThinkPHP5 Controllers

In ThinkPHP5 (TP5) controllers there are two main ways to render templates: using the view() helper function and the fetch() method, each with slightly different behavior.

When the controller does not inherit from the base controller, you can either instantiate a view object and call its fetch method:

// not inheriting controller
$view = new view();
return $view->fetch('index/demo');

or use the global view() helper directly:

// not inheriting controller
return view('index/demo');

If the controller extends the TP5 base controller, you can call fetch directly on $this:

// inheriting controller
return $this->fetch('index/demo');

The latter two approaches (the helper view() and the inherited $this->fetch()) support common configuration replacements such as tpl_replace_string (e.g., __CSS__) in templates, allowing paths and other variables to be injected automatically, whereas the first approach outputs the raw string.

For consistency and to leverage shared configuration, the article recommends using the helper view() or the inherited $this->fetch() in projects.

When you instantiate a view object directly, it cannot read the common configuration file; you must manually set parameters after creating the object, for example:

new view();
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendfetchPHPViewThinkPHP5
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.