Laravel is an MVC framework with its own folder structure, but sometimes we want to use something external which doesn’t follow the same structure. Let’s review two different scenarios – when we have external class and when it’s just a .php file.

Let’s say we have a simple example, a PagesController.php file like this:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
namespace App\Http\Controllers;
 
class PagesController extends Controller
{
  /**
   * Display homepage.
   *
   * @return Response
   */
  public function getHome()
  {
    return view('pages.home');
  }
 
}
 

Pretty simple, right? Now, let’s say we want to have our product prices on the homepage, but they come from some kind of external class or PHP file.

Use an external class in Controller

Let’s say we have a simple class to define the prices:

 
1
2
3
4
5
6
7
 
class PricesClass {
  public function getPrices() {
    return ['bronze' => 50, 'silver' => 100, 'gold' => 150];
  }
}
 

Now, where to put this class and how to use it? A couple of steps here:

1. You can put a class itself anywhere you want within \App folder

By default, Laravel offers you some folders there like Providers, but I personally prefer to create a separate one – like App\Libraries, App\Classes or App\Services. Or you can call it your own application – App\MyApp. This is totally your choice.

So, in this example, let’s save the class as App\Classes\PricesClass.php.

2. Namespace within the file

Now we have to tell Laravel what is the namespace of this new file – it’s the same as the folder:

 
1
2
3
4
5
6
7
8
 
<?php
 
namespace App\Classes;
 
class PricesClass {
// ...
 

3. Use the class in your Controller

Let’s get back to our PagesController.php – here we have to add use statement for that external class, and then we’re free to use it! Like this:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
namespace App\Http\Controllers;
 
use App\Classes\PricesClass;
 
class PagesController extends Controller
{
  /**
   * Display homepage.
   *
   * @return Response
   */
  public function getHome()
  {
    $pricesClass = new PricesClass();
    $prices = $pricesClass->getPrices();
    return view('pages.home', compact('prices'));
  }
 
}
 

That’s it, nothing more complicated than that.

Have you tried our tool to generate Laravel adminpanel without a line of code?
Go to QuickAdminPanel.com

Use an external PHP file in Controller

Another case – it’s not always an OOP file that we want to use. For some cases it’s just a list of functions. Of course, we can wrap them in a class as well, but not always. So, how to use the same function, if we just have a prices.php file like this:

 
1
2
3
4
5
6
7
 
<?php
 
function getPrices() {
  return ['bronze' => 50, 'silver' => 100, 'gold' => 150];
}
 

And that’s it – no class, no namespace, nothing.
Let’s place our function as app/functions/prices.php file. Then – we have three differentways of include it:

1. Just include the class with PHP functions like include() or require() – and don’t forget app_path() function:

 
1
2
3
4
5
6
7
 
public function getHome()
{
  include(app_path() . '\functions\prices.php');
  $prices = getPrices();
  // ...
 

Note that you still need a slash symbol before the folder functions.
You can read more about app_path() and other Helper functions in the official documentation.

2. In composer.json file you just add needed files in “autoload” section – in a new entry called “files”:
(thanks for this suggestion to the commenters Joseph and Hisham)

 
1
2
3
4
5
6
7
8
9
10
11
12
13
 
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
            "app/functions/prices.php"
        ]
    },
 

This way you don’t need to use any include() functions anywhere within your controllers – just use the functions straight away.

3. Autoload the whole folder in composer.json
(thanks to YOzaz for pointing this out in comments)

Another way is just autoload the folder with that file – so you would place any similar external “helpers” in that folder, and that would be included in the future. In this case – add this folder in array or “classmap”:

 
1
2
3
4
5
6
7
8
 
    "autoload": {
        "classmap": [
            "database",
            "app/functions"
        ],
    },
 

Choose this option if you want those files to be included in a manner of “set it and forget it”.

Notice: if you make these changes to composer.json file, don’t forget to run composer dump-autoload for changes to take effect.

Facebook
Twitter
Google+
LinkedIn
Check out my new online course: Laravel Eloquent: Expert Level 

How to use external classes and PHP files in Laravel Controller?的更多相关文章

  1. Portswigger web security academy:XML external entity (XXE) injection

    Portswigger web security academy:XML external entity (XXE) injection 目录 Portswigger web security aca ...

  2. Ant搭建 一键生成APP技术 平台

    1.博客概要 本文详细介绍了当今流行的一键生成APP技术.介绍了这种设计思想的来源,介绍了国内外的研究背景,并介绍了这个技术体系中的一些实现细节,欢迎各路大神们多提意见.一键生成技术,说的通俗点就是, ...

  3. KBMMW 4.90.00 发布

    kbmMW is a portable, highly scalable, high end application server andenterprise architecture integra ...

  4. Yii源码阅读笔记(十)

    控制器类,所有控制器的基类,用于调用模型和布局,输出到视图 namespace yii\base; use Yii; /** * Controller is the base class for cl ...

  5. UIkit框架介绍

    UIKit Framework The UIKit framework (UIKit.framework) provides crucial infrastructure for implementi ...

  6. Domain Driven Design and Development In Practice--转载

    原文地址:http://www.infoq.com/articles/ddd-in-practice Background Domain Driven Design (DDD) is about ma ...

  7. 译:Spring框架参考文档之IoC容器(未完成)

    6. IoC容器 6.1 Spring IoC容器和bean介绍 这一章节介绍了Spring框架的控制反转(IoC)实现的原理.IoC也被称作依赖注入(DI).It is a process wher ...

  8. android自动打包方法(ant+proguard+签名)

    前段时间做了一个android的网游项目,现在优化减少体积和防止别人反编译,需要把编译后.class进行混淆,开始在网上看了一些关于 ProGuard的介绍,基本上都是使用ADT自带的打包方式,那个打 ...

  9. yii2源码学习笔记(十一)

    Controller控制器类,是所有控制器的基类,用于调用模型和布局. <?php /** * @link http://www.yiiframework.com/ * @copyright C ...

随机推荐

  1. Global Illumination

    [Global Illumination] Global Illumination (GI) is a system that models how light is bounced off of s ...

  2. appium自动化测试之UIautomatorviewer元素定位

    appium自动化测试之UIautomatorviewer元素定位 标签(空格分隔): uiautomatorviewer元素定位 前面的章节,已经总结了怎么搭建环境,怎样成功启动一个APP了,这里具 ...

  3. python 内置函数(一),低阶内置函数功能汇总

    python  内置函数  68个 今日主要内容: 1.内置函数 一.内置函数 1.内置函数 详细细节内容地址(id):https://mubu.com/edit/odv-2Dkb6j

  4. 162. Find Peak Element (Array; Divide-and-Conquer)

    A peak element is an element that is greater than its neighbors. Given an input array where num[i] ≠ ...

  5. PTA 7-50 畅通工程之局部最小花费问题(最小生成树Kruskal)

    某地区经过对城镇交通状况的调查,得到现有城镇间快速道路的统计数据,并提出“畅通工程”的目标:使整个地区任何两个城镇间都可以实现快速交通(但不一定有直接的快速道路相连,只要互相间接通过快速路可达即可). ...

  6. FortiGate防火墙内存使用率高问题

    1.现象:zabbix监控到防火墙内存使用率频繁超过80%,而FortiGate防火墙内存超过80%将开启自身保护模式而不能新加策略等. 2.分析:这种情况一般是某些进程再释放内存的时候卡住.可以先查 ...

  7. Django具体操作(六)

    文章详情页的编写: {% extends "base.html" %} {% block content %} {% csrf_token %} <div class=&qu ...

  8. vue生产环境部署总结

    参考:http://www.cnblogs.com/vipstone/p/6910255.html 1. vue项目根目录/config/index.js更改资源生成路径 assetsPublicPa ...

  9. java 编解码

    decoder:解码--> 将文件内容转换为字符对象: encoder:编码-->将字符对象转换为字节或者字节数组: ASCII  (American Standard for Infor ...

  10. Day 07 文件的相关操作

    文件初始: 文件的三要素: path:文件的路径 mode:r w r+ w+ a encoding: 编码方式 # 打开一个文件的方法 f1 = open('e:\echo.txt', encodi ...