- Laravel Application Development Cookbook
- Terry Matula
- 225字
- 2021-07-23 15:33:32
Using Autoloader to map a class name to its file
Using Laravel's ClassLoader, we can easily include any of our custom class libraries in our code and have them readily available.
Getting ready
For this recipe, we need to set up a standard Laravel installation.
How to do it...
To complete this recipe, follow these steps:
- In the Laravel
/app
directory, create a new directory namedcustom
, which will hold our custom classes. - In the
custom
directory, create a file namedMyShapes.php
and add this simple code:<?php class MyShapes { public function octagon() { return 'I am an octagon'; } }
- In the
/app/start
directory, openglobal.php
and updateClassLoader
so it looks like this:ClassLoader::addDirectories(array( app_path().'/commands', app_path().'/controllers', app_path().'/models', app_path().'/database/seeds', app_path().'/custom', ));
- Now we can use that class in any part of our application. For example, if we create a route:
Route::get('shape', function() { $shape = new MyShapes; return $shape->octagon(); });
How it works...
Most of the time, we will use Composer to add packages and libraries to our app. However, there may be libraries that aren't available through Composer or custom libraries that we want to keep separate. To accomplish this, we need to dedicate a spot to hold our class libraries; in this case, we create a directory named custom
and put it in our app
directory.
Then we add our class files, making sure the class names and filenames are the same. This could either be classes we create ourselves or maybe even a legacy class that we need to use.
Finally, we add the directory to Laravel's ClassLoader. When that's complete, we'll be able to use those classes anywhere in our application.
See also
- The Creating advanced Autoloaders with namespaces and directories recipe
- Cisco OSPF命令與配置手冊(cè)
- 網(wǎng)絡(luò)協(xié)議工程
- Hands-On Industrial Internet of Things
- Windows Server 2003 Active Directory Design and Implementation: Creating, Migrating, and Merging Networks
- Bonita Open Solution 5.x Essentials
- 端到端QoS網(wǎng)絡(luò)設(shè)計(jì)
- 云工廠:開(kāi)啟中國(guó)制造云時(shí)代
- 園區(qū)網(wǎng)絡(luò)架構(gòu)與技術(shù)
- 計(jì)算機(jī)網(wǎng)絡(luò)技術(shù)
- 人際網(wǎng)絡(luò)
- 信息技術(shù)安全評(píng)估準(zhǔn)則:源流、方法與實(shí)踐
- 5G智慧交通
- 物聯(lián)網(wǎng),So Easy!
- 智慧的物聯(lián)網(wǎng):感知中國(guó)和世界的技術(shù)
- 國(guó)外物聯(lián)網(wǎng)透視