By: Povilas Korop

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 

转载于:https://www.cnblogs.com/mouseleo/p/9979418.html

How to use external classes and PHP files in Laravel Controller?相关推荐

  1. Lab: Exploiting XXE using external entities to retrieve files:利用外部实体利用 XXE 来检索文件...

    利用XXE检索文件 要执行从服务器的文件系统中检索任意文件的 XXE 注入攻击,您需要通过两种方式修改提交的 XML: 引入(或编辑)DOCTYPE定义包含文件路径的外部实体的元素. 编辑应用程序响应 ...

  2. c语言resource files的作用,VC中Source Files, Header Files, Resource Fil

    VC++6.0中Source Files,Header Files,Resource Files,External Dependencies区别 Source Files 放源文件(.c..cpp)程 ...

  3. Saving Files

    Saving Files 保存文件 Android uses a file system that's similar to disk-based file systems on other plat ...

  4. .gitignore过滤规则

    为什么80%的码农都做不了架构师?>>>    #.gitignore file for java eclipse project*target* *.jar *.war *.ear ...

  5. 《Deep Learning With Python second edition》英文版读书笔记:第十一章DL for text: NLP、Transformer、Seq2Seq

    文章目录 第十一章:Deep learning for text 11.1 Natural language processing: The bird's eye view 11.2 Preparin ...

  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. JDEManual2 Overview

    来源:http://aosgrp.com/ 2 Overview JACK™ Intelligent Agents supports two agent reasoning models: a bas ...

  8. Gradle 工具的源码研究

    Gradle 工具源码不是gradle wrapper 源码 安装android studio之后,Gradle 工具被缓存到 user/.gradle/cache/module-2/下面,不同的AS ...

  9. SAP Commerce(SAP Hybris)学习资料汇总

    版本号:v1.06 2020年11月24日 所有的架构图在这个单独的帖子里. 导航目录 SAP官方帮助文档 configuration 如何运行 Filters 容器化支持 Installer-Rec ...

最新文章

  1. 【NIO】通道Channel
  2. 实验进行中:.NET WebAssembly支持
  3. Ubuntu16.04安装CUDA8.0时,提示:The driver installation is unable to locate the kernel source.
  4. RelayCommand命令
  5. python求近似值_python 已知一个字符,在一个list中找出近似值或相似值实现模糊匹配...
  6. 95-190-742-源码-WindowFunction-AllWindowFunction
  7. 海南省重点公共场所WiFi覆盖率达到97.7%
  8. c语言中*在变量的右上角,C语言中变量的声明和定义
  9. 计算机查找的快捷键是,电脑快捷键快速查找
  10. GTX1060 Windows7/Windows8/Windows8.1 旧版显卡驱动下载链接
  11. undefined == null的正确解释
  12. 疯狂猜颜色小游戏C++个人项目
  13. 声表面波传感器的全球与中国市场2022-2028年:技术、参与者、趋势、市场规模及占有率研究报告
  14. 音视频开发:大华摄像头配置RTSP与RTMP地址访问视频画面
  15. 博客 / 论坛 / 书籍 / 维基百科 参考文献类型
  16. 【vivado IP核】第4篇:ILA使用介绍
  17. pyspark sql简单入门
  18. 洛谷P1014题解 [NOIP1999 普及组] Cantor 表
  19. 基于Python的网络拓扑图绘制
  20. Ubuntu深入学习

热门文章

  1. Minimum Inversion Number HDU - 1394(权值线段树/树状数组)
  2. Numbers on the Chessboard
  3. tensorboard : 无法将“tensorboard”项识别为 cmdlet、函数、脚本文件或可运行 程序的名称。
  4. 一个完整的gdb调试过程以及一些常用的命令
  5. ROS2学习(六).ROS概念 - 服务质量设置
  6. pcs7更改项目计算机名时出错,PCS7 C/S报警问题-工业支持中心-西门子中国
  7. 计组—双端口与多模块存储器
  8. linux-shell命令之chown(change owner)【更改拥有者】
  9. LLVM4更新--简化对象定义
  10. 人可以拒绝任何东西,但绝对不可以拒绝成熟