prwhitehead / meagr
框架辅助类和类库
Requires
- php: >=5.3.0
- imagine/imagine: dev-develop
- phpmailer/phpmailer: dev-master
This package is not auto-updated.
Last update: 2020-01-10 14:49:04 UTC
README
A small, focused framework for small-ish projects that require an aspect of H/MVC and a lightweight MySQL ORM/Model. With a bootstrap Form class, Environment specific config, CSS/JS/HTML Caching, S3 interface, Encryption, Validation, automatic db schema creation, Auth, Timer, Nonce and helpers for Inputand Arrays.
目录结构
Meagr 允许你在设置应用程序时具有一定的灵活性。主要系统类集可以在 composer 包中找到,该包通过在你的 composer.json 文件中添加以下 require 命令添加到你的 vendor 文件夹中
"require": {
"prwhitehead/meagr": "dev-master"
}
一旦文件安装并准备就绪,你必须设置你的模块/应用程序文件夹。由于非 composer 自动加载器的工作方式,你放置文件的任何文件夹都将定义你的命名空间。
这些文件是路由、配置等所必需的。'modules' 文件夹是你的应用程序将放置的位置。它被称为 'modules' 而不是 'app' 或 'application',因为每个模块都可以是一个独立的微应用程序,执行一组特定的任务。
模块的命名空间应如下所示
/Modules/YourModulesName
此命名空间与你的控制器/模型/视图文件夹的文件夹名称和结构相匹配
/Modules/YourModulesName/Controllers/Classname
子控制器也可以通过在文件名中使用下划线来使用。
/admin/user/create
首先会查找一个包含 GET_user 方法的 Admin 控制器类,并将 'create' 作为变量传递。下一个检查会查找位于 admin 应用文件夹中的 admin_user.php 中的 Admin_User 控制器。
/modules/admin/controllers/admin_user.php
对于方法
Admin_User::GET_create();
路由
默认情况下,网站可以使用 MVC 或 HMVC 结构,它使用
http://www.example.com/news/latest
这将路由到以下内容
modules/news/controllers/news.php
或
modules/controllers/news.php
HMVC 结构优先于 MVC,这是默认设置。
如果我们为我们的应用程序模块使用 HMVC 结构,系统将查找以下类和方法
<?
Modules\News\Controllers\News::GET_latest();
如果参数数量是偶数,系统将尝试将它们分配为键 => 值对。因此,以下 URL
<your domain>/admin/user/add/this/that/and/again/hi
在找到方法 Admin_User::GET_add() 后应解析为数组
<?
Array
(
[add] => this
[that] => and
[again] => hi
)
原始 URI 段总是作为名为 $segments 的数组传递,如果段的数量是偶数,则 $pairs 将包含解析的键 => 值对。因此,以下 URI
<your domain>/admin/user/something/else/that/is/passed/as/segments/again/
将转换为访问 Admin_user 类,如果没有找到 GET_something() 方法,系统将检查默认控制器(通常是 GET_index()),然后将以下数组传递给该方法,如果找到
<?
Array
(
[segments] => Array
(
[0] => admin
[1] => user
[2] => something
[3] => else
[4] => that
[5] => is
[6] => passed
[7] => as
[8] => segments
[9] => again
)
[pairs] => Array
(
[something] => else
[that] => is
[passed] => as
[segments] => again
)
)
使用视图
要在你的控制器中包含一个视图,请使用以下方法
<?
echo \Meagr\View::view('ModulesName::view-filename');
将数据传递到位于网站默认 app/view 文件夹中的简单视图文件
<?
\Meagr\View::view('test', compact('data'));
使用模型
<?
$news = Modules\Models\News::init()->tableAlias('n')
->distinct()
->where('n.title', 'tes%', 'LIKE')
->where('n.created_at', '0000%')
->orderDesc('n.id')
->limit(2)
->offset(3)
->go();
返回
<?
Array
(
[0] => Modules\News\Models\News Object
(
[id] => 4
[title] => testing
[slug] => testing
[content] => This is the content of the first testing news article
[parent] => 9
[created_at] => 0000-00-00 00:00:00
[updated_at] => 0000-00-00 00:00:00
)
[1] => Modules\News\Models\News Object
(
[id] => 3
[title] => testing
[slug] => testing
[content] => This is the content of the first testing news article
[parent] => 9
[created_at] => 0000-00-00 00:00:00
[updated_at] => 0000-00-00 00:00:00
)
)
由于数据库类实现了 PHP SPL ArrayAccess,我们也可以这样做
<?
//get member
$member = Modules\Models\Member::init()->where('id', $id);
//the count function will trigger the go() method and generate our results (lazy loading)
if (count($member)) {
//now we have access to member
p($member);
}
配置
为了为开发/生产/预演等服务器使用不同的配置,请在你的应用程序文件夹中添加一个 'config' 文件夹,以环境作为子文件夹,并包含一个在其中的配置.php 文件。要使用的环境由 "ENVIRONMENT" 常量设置,因此
<?
define("ENVIRONMENT", 'production');
这意味着系统将查找以下类
::php
<?
namespace Modules\Config\Production\Config();
这将匹配
modules/config/production/config.php
作为备用方案,如果您希望应用程序中只使用一个配置文件,请将其包含在基本配置目录中,它将被包含在内。
输入
用于获取和设置 $_GET、$_POST、$_SESSION 和 $_COOKIE 的值。
<?
echo \Meagr\Input::get('param_name');
设置值
<?
\Meagr\Input::get('param_name', 'value');
Bcrypt
实例化 Bcrypt();
<?
$b = new \Meagr\Bcrypt();
对密码/输入数据进行哈希处理
<?
$password = $b->hash('mypassword01');
获取 Bcrypt 类此实例的盐
<?
$salt = $b->getSalt();
现在您可以存储盐与用户密码在一起,并在下次用户通过登录时验证它
<?
$new = new Bcrpyt();
$new->setSalt($user_salt);
if ($new->verify('mypassword01', $users_password_from_db)) {
return true;
}
计时器
计时器类用于查看事件花费的时间,并基于“多例”模式工作
使用您的名称初始化计时器,在本例中为 'db'
<?
\Meagr\Timer::init('db');
输出自计时器启动以来经过的时间差
<?
echo \Meagr\Timer::init('db')->diff();
或者您可以使用
<?
\Meagr\Timer::init('db')->stop();
...稍后
<?
echo \Meagr\Timer::init('db')->diff();
成员
按照以下方式将用户添加到成员表中。首先实例化 Bcrypt 类,并生成用户的唯一盐,然后您可以对他们的密码进行哈希处理。
<?
$b = new \Meagr\Bcrypt();
$salt = $b->getSalt();
$password = $b->hash('123');
现在我们可以创建一个成员对象的新实例并将其保存到数据库中。
<?
$test = new Modules\Models\Member();
$test->email = 'users@emailadderss.com';
$test->password = $password;
$test->salt = $salt;
$test->first_name = 'first-name';
$test->last_name = 'lastname';
$id = $test->save();
工作完成了一半。现在我们可以在函数和方法中检查用户是否有效,方法如下
<?
$member = Modules\Models\Member::init()->where('email', $email);
//check the user exists first
if (count($member)) {
//get the first index in results
$member = $member[0];
//init the Bcrypt class and set the instance's salt to the members db salt
$crypt = new \Meagr\Bcrypt();
$crypt->setSalt($member->salt);
//now we can check to see if the users password matches our hash with the users salt
if ($crypt->hash($password) == $member->password) {
//the password matches, so create the session.
//we can get user data with \Meagr\Auth::current() which returns a Model object of member data
\Meagr\Auth::create($member->id);
// \Meagr\Router::redirect('/member/dashboard');
//if the passwords dont match, force logout
} else {
\Meagr\Auth::destroy();
\Meagr\Router::redirect('/member');
}
//the memeber couldnt be found
} else {
throw new \Meagr\MeagrException('User not found');
}
注销用户或取消设置他们的会话要容易得多
<?
\Meagr\Auth::destroy();
表单类
创建一个类似于以下的新表单
<?
$form = Meagr\Form::init(array(
'id' => 'form_id',
'class' => 'standard-form',
'method' => 'get',
'action' => '/admin/user/new',
));
在这里,我们传入我们的表单设置数据数组,包括所有正常的表单标签属性。
现在您可以通过 addFields() 或 addField() 添加输入字段数据。后者只期望一个输入数据的单维数组,而前者只接受一个多维数组,如以下示例所示
<?
$form->addFields(
array(
'email' => array(
'id' => 'email',
'name' => 'email',
'class' => 'form-element ',
'label' => 'Email Address',
'help' => 'Please enter a valid email address',
'placeholder' => 'john@smith.com',
'type' => 'text',
'validate' => array(
'not' => array(
//key is the type of check
//value is the message upon failure
'empty' => 'An email address must be provided'
),
'is' => array(
'string' => 'A string is required'
),
'valid' => array(
'email' => 'A valid email is required',
'gmail' => 'A gmail email address must be provided'
)
),
'append' => array(
'type' => 'span',
'value' => 'Options',
'options' => array(
'action' => array(
'id' => 'action',
'title' => 'Action',
'icon' => '',
'href' => \Meagr\Router::redirect('/admin/login', false)
),
'second_action' => array(
'id' => 'second_action',
'title' => 'Second Action',
'href' => \Meagr\Router::redirect('/admin/login', false)
),
'divider' => true,
'third_action' => array(
'id' => 'third_action',
'title' => 'third Action',
'href' => \Meagr\Router::redirect('/admin/login', false)
),
)
),
'value' => \Meagr\Input::post('email'),
'password' => array(
'id' => 'password',
'name' => 'password',
'class' => 'form-element',
'label' => 'Password',
'type' => 'password',
'validate' => array(
'not_empty',
'is_string'
),
'value' => ''
),
'submit' => array(
'id' => 'submit',
'name' => 'submit',
'class' => 'form-element',
'label' => '',
'type' => 'submit',
'validate' => array(),
'value' => 'Submit'
),
)
);
'append' 数组创建下拉菜单。
数组中未明确用于表单类中的所有项目都转换为属性和值,因此
<?
'email' => array(
'id' => 'email',
'name' => 'email',
'class' => 'form-element ',
'label' => 'Email Address',
'help' => 'Please enter a valid email address',
'placeholder' => 'john@smith.com',
将自动创建
<input placeholder="john@smith.com" help="Please enter a valid email address" class="form-element" id="email" name="email" />
验证要求如下
<?
'validate' => array(
'not' => array(
//key is the type of check
//value is the message upon failure
'empty' => 'An email address must be provided'
)
)
这会将输入值传递给 Validate 类,Validate::not() 方法用于检查值是否不为 'empty',如果值为空,则返回提供的信息。
可以通过以下方式将 HTML 添加到表单中
<?
$form->addHTML('<div class="container">');
稍后,您可能需要关闭 div
<?
$form->addHTML('</div>');
设置好您喜欢的表单后,使用 build() 方法将其输出到屏幕
<?
$form->build();
Nonce 类
Nonce 类用于验证系统发出的请求,包括表单输入和 URL 动作。
首先创建您的 nonce 表单输入字段如下
<?
\Meagr\Nonce::input('nonce-name');
现在,为了检查我们的请求是否来自网站中的授权用户
<?
if (\Meagr\Nonce::valid($_POST['_nonce'], 'nonce-name')){
//do stuff as request is valid
}
我们还可以创建我们的请求的 GET 请求
<a href="index.php?<?=\Meagr\Nonce::string('nonce-name'); ?>">Link One</a>
它以相同的方式进行验证
<?
if (\Meagr\Nonce::valid($_GET['_nonce'], 'nonce-name')){
//do stuff as request is valid
}
Arr(数组类)
使用 . 来分隔数组级别
<?
$array = array(
'one' => array('oneone' => 'hello', 'onetwo' => 'sup'), 'two' => 'goodbye', 'three' => 'one', 'four' => 2, 'five' => '3'
);
<?
p(\Meagr\Arr::get($array, 'one.onetwo'));
\Meagr\Arr::set($array, 'one.onetwo', 'init');
p(\Meagr\Arr::get($array, 'one.onetwo'));
Amazon AWS S3
在 Config::s3() 数组中输入存储桶名称、密钥和密钥。然后您可以使用以下方法创建存储桶
<?
$s3 = \Meagr\s3::init();
$s3->createBucket('testing_bucket_name');
列出您的存储桶,从 Config::s3() 方法中输入的详细信息
<?
$buckets = $s3->listBuckets();
if (! empty($buckets)) {
foreach($buckets as $bucket) {
//do stuff
}
}
在创建之前测试存储桶是否存在
<?
$b = 'newish';
if (! $s3->bucketExists($b)) {
$s3->createBucket($b);
}
检查存储桶当前存储的位置
<?
echo $s3->getBucketLocation('testing_bucket');
在继续之前测试存储桶是否存在以及是否已上传文件
<?
$file = PUBLIC_PATH . '/css/bootstrap.css';
$bucket = 'newish';
if ($s3->bucketExists($b) and $s3->addFile($file, $bucket)) {
//do stuff
}
//now we can get a list of the bucket contents
$contents = $s3->getBucket($bucket);
当打印到屏幕时,$contents将包含类似以下内容
<?
p($contents);
//produces
Array
(
[README.text] => Array
(
[name] => README.text
[time] => 1358636456
[size] => 22845
[hash] => 05316005760d05b7358214fa4d569aa3
)
[bootstrap.css] => Array
(
[name] => bootstrap.css
[time] => 1358680587
[size] => 120125
[hash] => 444737d256d564959f9b9abb84aa94cc
)
[debug.css] => Array
(
[name] => debug.css
[time] => 1358637424
[size] => 0
[hash] => d41d8cd98f00b204e9800998ecf8427e
)
)
要获取存储在s3桶中的文件的 内容
<?
//request the file by its filename and the bucket name
$file = $s3->getFile('bootstrap.css', $bucket);
要从桶中删除文件
<?
$s3->deleteFile('bootstrap.css', $bucket);
要从一个桶复制文件到另一个桶
<?
$copy = $s3->copyFile($new_filename, $new_bucket, $current_filename, $current_bucket));
如果复制成功,则copy将返回bool true。
Caching PHP -> HTML
缓存系统非常简单。如果文件夹不存在,则会自动创建文件夹,并在网站/应用程序配置Cache()方法中初始化所有值。在此,设置了两个数组键,'dir'和'duration'。目录将根据网站路径和'dir'值创建。以秒为单位的时间将控制文件重创建的频率。所有文件都是URL特定的,因此您可以在'duration'索引中指定的时间内缓存主页、关于等。
除了输出缓存外,还有CSS和JS合并以节省HTTP请求。
以下是从Response类中摘取的一段代码,用于检查当前URI是否与HTML缓存文件相关联,如果没有找到,或者文件创建以来经过的时间已超过我们的时间限制,则会创建一个新的文件并返回给用户。
<?
//init with the default key which is then turned into our current URI
$cache = Cache::init();
//if cache is available and within the time limit, which we are over ridding to be 1 minute
if ($cache->setDuration(60)->exists()) {
//get the cache and assign to a variable which can be echo'ed or manipulated
$body = $cache->get();
//if the cache doesnt already exist, or the time limit has expired
} else {
//now can set the body and the time limit
$cache->set($body, 60);
}
CSS / JS合并
系统允许将CSS文件添加到传递给缓存类的数组中,然后合并在一起。与HTML一样,每次都会添加和检查缓存超时。数组中每个文件的最后修改时间也会进行检查,以确保自缓存创建以来没有任何文件被更新。
这应放在模板的头部
<? /*incude the css files in the cache file */
$array = array(
PUBLIC_PATH . "/css/normalize.css",
PUBLIC_PATH . "/css/bootstrap.css",
PUBLIC_PATH . "/css/main.css"
); ?>
<link rel="stylesheet" href="<?=\Meagr\Cache::init('css')->concat($array)->file ;?>">
或者,通过将init('css')更改为init('js'),可以从Config::cache()方法的值数组中获取JavaScript文件名并使用。
<? /*incude the javascript files in the cache file */
$array = array(
PUBLIC_PATH . "/js/vendor/modernizr-2.6.2.min.js",
PUBLIC_PATH . "/js/vendor/jquery-1.8.2.js",
PUBLIC_PATH . "/js/bootstrap-dropdown.js",
PUBLIC_PATH . "/js/bootstrap-tab.js",
); ?>
<script src="<?=\Meagr\Cache::init('js')->concat($array)->file; ?>"></script>
钩子和钩接
Meagr允许您使用简单的钩接系统绑定和触发操作。要绑定稍后触发的操作,您必须提供事件名称,然后是一个包含字符串或类的实例(字符串形式的类名和字符串形式的函数名)的数组。
第一个示例使用两个字符串,或类名和函数名
<?
\Meagr\Hook::bind('header', array('Home', 'additionalCss'));
第二个示例提供一个包含对象实例和字符串形式的函数名的数组的示例
<?
\Meagr\Hook::bind('header', array(new Home, 'additionalCss'));
然后可以在您的代码中触发钩子
<?
$css = Meagr\Hook::trigger('additionalCss');
foreach($css as $file){
//do stuff
}
触发结果将数据数组分配给变量,因此必须循环等以访问数据。钩子可以在类的__before()方法中绑定,这样就可以将其提供给类中的所有方法。
电子邮件 + SMTP
Meagr有一个Email类,该类允许通过PHPMailer类的简单包装使用SMTP进行邮件发送。每个Email类方法都返回$ this,从而允许方法链。
<?
//initialise the class
\Meagr\Email::init()
//add from address, if not provided, the default from the site / environment config will be used
->addFrom('paul@prwhitehead.co.uk', 'Paul Whitehead')
//add our subject
->addSubject('This is the subject of our email')
//add an address name => $name, email => $email
->addAddress('youraddress@domain.com', 'Paul Whitehead')
//add a multidimentional array of addresses
// ->addAddresses($array)
//add a bcc'd address
->addBCC('prwhi@prw.com', 'Paul Whitehead')
//add a cc's address
->addCC('prwhi@prw.com', 'Paul Whitehead')
//add the header html, if this is not provided, the site config is used
// ->addHeader('/the/file/path/location/of/the/file.php')
//add the footer html, if this is not provided, the site config is used
// ->addFooter('/the/file/path/location/of/the/file.php')
//add an attachment
->addAttachment(PUBLIC_PATH . '/index.php')
//add the content via a callback class/method (methods must echo content)
->addContent(array(__NAMESPACE__ . '\Home', 'email'), array('one' => 'hello', 'two' => 'goodbye'))
//dont send but output to the screen, remove this to send live emails
->debug(true)
//send and return self
->go();
可以通过类方法添加内容,该类方法将输出内容,然后将其缓冲并添加到要发送的电子邮件内容中。在上面的addContent()方法中,传入一个包含完全限定命名空间和名为'email'的类的名称的数组,还可以传入一个可选的值数组,该数组在电子邮件内容中被提取。email()方法可以如下所示
<?
namespace Modules\Controllers;
class Home {
public static function email() {
//if a partial is used via the View class, it must be echoed
echo \Meagr\View::partial('email-content', func_get_args());
}
一些值通过网站/环境配置设置,然后用于配置默认值以及SMTP认证值
<?
class Config {
public static function email() {
return array(
'header' => MODULE_PATH . '/views/partials/email-header.php',
'footer' => MODULE_PATH . '/views/partials/email-footer.php',
'from-address' => 'prwhitehead@gmail.com',
'from-name' => 'Paul Whithed',
'smtp' => false,
'smtp-port' => '465',
'smtp-username' => 'prwhitehead@gmail.com',
'smtp-password' => 'your-password',
'smtp-host' =>'ssl://smtp.gmail.com'
);
}
FTP
Meagr有一个简单的FTP接口,允许上传和下载文件,删除、复制和移动文件,创建和删除目录。它不是设计为全面的,而是允许快速轻松地完成大多数任务。
FTP类可以用来同时连接多个FTP服务器,方法是将它们的详细信息添加到Config类的ftp()方法中,如下所示:
<?
class Config {
static function ftp($connection_name = 'default') {
return array(
'default' => array(
//details
),
'backup' => array(
//details
)
)
}
当实例化FTP类时,$connection_name变量用于确定要使用哪套连接详情。这是提供这些详情的主要方法,然而,在实例化后也可以添加其他详情。
要实例化FTP类并使用默认连接详情连接到服务器
<?
$ftp = \Meagr\FTP::init('default');
$ftp->connect();
还支持方法链式调用
<?
$ftp = \Meagr\FTP::init('default')->connect();
要导航FTP服务器文件夹结构,可以使用cd()方法。传递您想要导航到的目录。每次更改目录时,FTP类都会记录当前工作目录,并通过pwd()方法访问。因此,要从根服务器级别移动到子文件夹,可以使用
<?
//change to a subfolder called 'wp-content'
$ftp->cd('/wp-content');
//return the directory contents as an array
$contents = $ftp->lsPwd();
//move to another subdirectory called 'db-backup'
$ftp->cd($ftp->pwd() . '/backup-db');
当FTP类无法执行操作时,它会抛出异常,因此请在try/catch块中包装您的命令
<?
try{
$ftp->mkdir('test');
} catch(MeagrException $e){
echo $e->getMessage();
}
...或者您也可以简单地这样做,并使用inDir()方法,该方法在返回布尔结果之前会检查当前目录列表
<?
//check for a directory within the present working directory
if (! $ftp->exists('test')) {
//and if not found, create it
$ftp->mkdir('test');
}
要上传或下载当前连接的文件,可以使用以下方法
<?
//push a file to the current working directory
$ftp->putFile(PUBLIC_PATH . '/css/bootstrap.css');
//get a file called 'bootstrap.css' from the current working directory and put it in the PUBLIC_PATH
$ftp->getFile('bootstrap.css', PUBLIC_PATH);
要从连接中删除文件
<?
//if no /directory/structure is passed, the class assumes that
//you wish to delete the file from the present working directory
$ftp->rmFile('bootstrap.css');
要更改文件的访问模式(chmod),可以执行以下操作
<?
//a string is required, which will be padded to the required 4 characters
$ftp->chmod('bootstrap.css', '777'); //equates to 0777
要重命名文件,只需添加文件和新名称,类将假定需要添加当前工作目录
<?
$ftp->rename('bootstrap.css', 'b.css');
但是,重命名可以用来移动文件和文件夹,通过将目录传递给第二个参数
<?
$ftp->rename('bootstrap.css', '/home/bootstrap.css');
调试
为了允许您调试应用程序并记录其行为,Meagr内置了一个灵活的Debug类并在使用中。
<?
//init the class and pass in the the collection name, which in this case is 'log'
\Meagr\Debug::init('log')->add(
//pass in an array of key => value pairs
array(
//our message
'message' => 'Load Controller Before',
//the class that is calling plus the method
'class' => __METHOD__,
//our status is used to group logs
'status' => 'success',
//use this to prevent using tons of memory when not in debug mode
'backtrace' => Debug::backtrace())
);
您可以为日志传递任何一组键值对,这也是为什么Debug类如此灵活的原因。Debug::output()方法将使用第一条记录中的键,并从那时起使用它们。
<?
//to print our log
echo \Meagr\Debug::init('log')
//and request only items with a 'success' status, an array of status's can also be passed
->output('success');
语言
通过使用单独的语言文件,Meagr支持通过在'core/helpers.php'文件中找到的传统__()函数交换语言字符串。
<?
echo __('my short sentence');
此函数是OOP方法的包装器
<?
//pass in our LANG_CODE, which should match the name of the file in our language folder
\Meagr\Language::init(LAMG_CODE)->get($language_string, $default);
语言文件必须与LANG_CODE匹配,并以前缀'.php'开头。因此,如果LANG_FILE设置为'EN',则Meagr将在以下位置检查名为$language的数组
/* our default location */
<SITE_PATH>/meagr/modules/config/en.php
/* also checking for environmental locations as well as subdomain apps */
<SITE_PATH>/meagr/modules/config/development/language/en.php
在我们的'en.php'文件中,我们需要简单地创建一个键值对数组,键与上面提到的$language_string匹配。
<?
$language = array(
'hello' => 'hello, welcome to my site',
'description' => 'description of my site'
);
反馈
反馈类可用于存储有关表单反馈的会话数据或任何需要在页面刷新或提交到其他地方时召回的数据。
<?
//initialise the type of feedback we want to give
$feedback = \Meagr\Feedback::init('errors');
//set the feedback message for the group 'form' this would be general feedback
$feedback->set('Sorry the form was invalid', 'form');
//add an email input error message
$feedback->set('The email address was invalid', 'email_address');
//check to see if we have feedback for the 'form' group
if ($feedback->exists('form')) {
//show() loops through the 'form' group array and outputs a string of div's
echo $feedback->show('form');
}
//check to see if we have feedback for the 'email_address' group
if ($feedback->exists('email_address')) {
//show() loops through the 'email_address' group array and outputs a string of div's
echo $feedback->show('email_address');
}
图像
创建一个简单缩略图,宽度100px,高度80px
<?
\Meagr\Image::init()
->open(PUBLIC_URL . '/test.jpg')
//create a new image, passing width / height
->thumb(100, 80)
//save to disk and return the locaiton of the new image
->save();
//we can how echo out our image
echo '<img src="' . $t . '" />';
大多数可用选项如下所示
<?
$t = \Meagr\Image::init()
//open a file to be read
->open(PUBLIC_PATH . '/test.jpg')
//set the cache limit or false
->cache(60)
//set width / height
->resize(500, 400)
//set the width and height as well as the crop coordinates
->crop(100, 100, 80, 80)
//set angle
->rotate(180)
//set flatten to false for gif/png
->flatten(false)
//set quality
->quality(10)
//override resolution for X and Y - NOT supported in GD Library
->resolutionX(100)
->resolutionY(100)
//write the file, return the saved location
->save();
//we can how echo out our image
echo '<img src="' . $t . '" />';
要将目录内容转换为拼贴画,可以使用以下方法
<?
//loop through our directory and record the images
foreach (glob(PUBLIC_PATH . '/images/*.png') as $path) {
$array[] = $path;
}
$t = \Meagr\Image::init()
//we have to set the name before the rest of the functions run
->setSaveFileName(PUBLIC_PATH . '/collage.jpg')
// cache the image for ever, if this was an int (ie 600) the image would be rebuild after an hour
->cache(true)
//create a new image, passing width / height
->create(1140, 150)
//add filepaths to be added to the collage and each ones size
->collage($array, 95, 75)
//save to disk
->save();
//we can echo our the class and it gives us either the saved image or if
//that hasnt been created, the original image back
echo '<img src="' . $t . '" />';