## 依赖的库
之前有个项目用做了扫描枪用的条形码生成。
就给大家演示下。
官网是
![](https://box.kancloud.cn/2015-11-28_565979750527d.png)
下载了最新版。
然后我们把这种第三方库放入vendor里去
![](https://box.kancloud.cn/2015-11-28_565979752edb2.png)
注意不同的码类型使用对应不同的class。
## 效果
![](https://box.kancloud.cn/2015-11-28_5659797541c2a.png)
大家可以修改生成的文本 参数 text。我演示的是code39。
## 实现代码
具体文件 随书项目 yang_book/examples/startup/BarcodeController.php
~~~
public function index(){
$class_dir = VENDOR_PATH.'barcodegen/class/';
// dump(is_file(VENDOR_PATH.'barcodegen/html/header.php'));
// die;
require($class_dir.'BCGFont.php');
require($class_dir.'BCGColor.php');
require($class_dir.'BCGDrawing.php');
// Including the barcode technology
include($class_dir.'BCGcode39.barcode.php');
// Loading Font
$font = new \BCGFont($class_dir.'font/Arial.ttf', 18);
// The arguments are R, G, B for color.
$color_black = new \BCGColor(0, 0, 0);
$color_white = new \BCGColor(255, 255, 255);
$code = new \BCGcode39();
$code->setScale(2); // Resolution
$code->setThickness(30); // Thickness
$code->setForegroundColor($color_black); // Color of bars
$code->setBackgroundColor($color_white); // Color of spaces
$code->setFont($font); // Font (or 0)
$code->parse(I('text', 'HELLO')); // Text
/* Here is the list of the arguments
1 - Filename (empty : display on screen)
2 - Background color */
$drawing = new \BCGDrawing('', $color_white);
$drawing->setBarcode($code);
$drawing->draw();
// Header that says it is an image (remove it if you save the barcode to a file)
header('Content-Type: image/png');
// Draw (or save) the image into PNG format.
$drawing->finish(\BCGDrawing::IMG_FORMAT_PNG);
}
~~~
其实就是改了原来的示列。
值得注意的是对于第三方类库的引用。
我们有几种加载第三方类库的方式:命名空间、import、vendor、
原生include和require
1. 命名空间适合于独立类,或者说这个类的构造方法处理其他文件的加载。常见的如ThinkPHP/Libary/Think下的所有类 如Upload、Page。
2. import适合默认类名符合tp类的规范即后缀是`.class.php`。import时系统会自动识别导入类库文件的位置,ThinkPHP可以自动识别的类库包包括Think、Org、Com、Behavior和Vendor包,以及Library目录下面的子目录 当然支持自定义位置和.php后缀,就是使用比较麻烦。
3. vendor 如果你的第三方类库都放在Vendor目录下面,并且都以.php为类文件后缀,也没用采用命名空间的话,那么可以使用系统内置的Vendor函数简化导入。
4. 原生require 或include 这里注意 路径字符串中的 './'不是当前文件位置而是框架入口。为了防止出错,我们也可以借用系统路径常量 如APP_PATH、VENDOR_PATH 来拼接。
载入一个类,如果报错了。怎么调试?我们可以通过将路径拼接到一个变量里。然后用is_file去判断:
如上面代码里的:`// dump(is_file(VENDOR_PATH.'barcodegen/html/header.php'));`
其实文件路径问题其实就是这么简单。
还有一个注意点,有的时候相对路径可能会报错,我们需要将其用realpath转换成全路径去对比。还有windows下路径中文要转gbk编码的问题。
## 效果
![](https://box.kancloud.cn/2015-11-28_5659797555b5a.png)