fax service website
PSR-Huh? – Tuts+ Code Tutorial
original source : http://code.tutsplus.com/tutorials/psr-huh–net-29314
if you’re an avid PHP developer, it’s quite likely that you’ve come across the abbreviation, PSR, which stands for “PHP Standards Recommendation.” At the time of this writing, there are four of them: PSR-0 to PSR-3. Let’s take a look at what these are, and why you should care (and participate).
A Brief History
PHP has never truly had a uniform standard for writing code. Those who maintain various codebases commit time to writing their own naming conventions and coding style guidelines. Some of these developers choose to inherit a well-documented standard, such as PEAR or Zend Framework; yet others choose to write standards completely from scratch.
The Framework Interoperability Group
Do not hesitate to open a new topic in the mailing list.
At the php|tek conference in 2009, people representing various projects discussed their options for working between projects. It surely comes as no surprise that sticking to a set of standards between codebases was the main agenda item.
Until recently, they labeled themselves as the “PHP Standards Group”, but now, they operate under the umbrella, Framework Interoperability Group (FIG). As they felt, the former didn’t accurately describe the group’s intentions. Even though the name of this group explicitly refers to frameworks, developers representing all sorts of projects have been accepted as voting members.
The FIG intends to host a cross-section of the PHP ecosystem, not exclusively framework developers. For example, the Symfony, Lithium and CakePHP frameworks each have a representative as a voting member, but the same goes for PyroCMS, phpDocumentor, and even Composer.
The voting members can start or participate in votes, however, anyone else (including you!) can become a PHP-FIG community member by subscribing to thePHP-FIG mailing list.
This mailing list is where discussions, votes, suggestions and feedback take place.
The Goal
The goal of the FIG is to create a dialogue between project representatives, with the aim of finding ways to work together (interoperability). At the time of this writing, that dialogue has spawned four PHP Standards Recommendations: PSR-0 to PSR-3.
Those recommendations are free and can be adopted by anyone, though no one is obligated to do so. In fact, voting members are not required to implement any of the PSRs in the projects that they represent!
PSR-0: Autoloader Standard
PSR-0 is a huge step forward for reusable code.
Remember how you used to specify many require
statements to reference all of the classes you require? Thankfully, this pattern changed with PHP 5’s magic__autoload()
function. PHP 5.1.2 made autoloading even better by introducingspl_autoload()
, which allows you to register a chain of autoloading functions withspl_autoload_register()
.
No matter how good the autoloading functionality is, it does not define how to implement it with existing codebases. For example, library X might approach the directory and classname structure differently than library Y, but you might want to use both!
Writing a proper autoloader that knows where to look for all possible fully-qualified names, as well as test all file extensions (.class.php, inc.php, .php etc) will quickly become a mess. Without a standard to define how to name classes and where to place them, autoloader interoperability would still be a pipe dream.
Meet PSR-0. A standard recommendation that describes “the mandatory requirements that must be adhered to for autoloader interoperability.”
PSR-0 is a huge step forward for reusable code. If a project follows the PSR-0 standard and its components are loosely coupled, you can simply take those components, place them within a ‘vendor’ directory, and use a PSR-0 compliant autoloader to include those components. Or, even better, let Composer do that for you!
For example, this is exactly what Laravel does with two Symfony Components(Console and HttpFoundation).
The FIG has an example implementation of a PSR-0 compliant autoloader function that can be registered to spl_autoload_register()
, but you are free to use any of the more flexible implementations, such as the decoupled Symfony ClassLoader orComposer’s autoloader.
PSR-1: Basic Coding Standard
PSR-1 focuses on a basic coding standard.
There was a lengthy period of low-activity in the FIG after PSR-0’s acceptance. In fact, it took a good year and a half before the PSR-1 and PSR-2 documents were approved.
PSR-1 focuses on a basic coding standard. It refrains from being too detailed, and does so by limiting itself to a set of ground rules to “ensure a high level of technical interoperability between shared PHP code”.
- Only use the
<?php
and<?=
tags. - Only use UTF-8 without BOM for PHP code.
- Separate side-effects (generate output, access a database etc.) and declarations.
- Enforce PSR-0.
- Class names must be defined in StudlyCaps.
- Class constants must be defined in upper case with underscore separators.
- Method names must be defined in camelCase.
The ground rules focus on naming conventions and file structure. This ensures that all shared PHP code behaves and looks the same way at a high level. Imagine an application that uses numerous third-party components, and they all use different naming conventions and character encodings. That would be a mess!
PSR-2: Coding Style Guide
PSR-2’s purpose is to have a single style guide for PHP code that results in uniformly formatted shared code.
PSR-2 extends and expands PSR-1’s basic coding standards. Its purpose is to have a single style guide for PHP code that results in uniformly formatted shared code.
The coding style guide’s rules were decided upon after an extensive survey given to the FIG voting members.
The rules in PSR-2, agreed upon by the voting members, do not necessarily reflect the preferences of every PHP developer. Since the FIG’s beginning, however, the PHP-FIG has stated that their recommendations have always been for the FIG itself; others willing to adopt the recommendations is a positive outcome.
The full PSR-2 specification can be found in the fig-standards repository. Be sure to give it a read.
In an ideal world, every PHP project would adopt the recommendations found in PSR-1 and PSR-2. However, due to taste (i.e. “Naming convention x looks better than y!”, “Tabs over spaces!”) and historical segmentation between various coding styles, there have only been a sparse amount of PHP projects adopting PSR-1 and PSR-2 in its entirety.
PSR-3: Logger Interface
PSR-3 describes a shared logging interface.
PHP Standard Recommendation #3 is the most recent addition to the accepted FIG-standards. It was accepted on December 27, 2012 with an impressive vote count of 18 to 0 (8 voting members did not cast a vote).
PSR-3 describes a shared logging interface, incorporating the eight Syslog levels ofThe Syslog Protocol (RFC 5424): debug, info, notice, warning, error, critical, alert and emergency.
Those eight Syslog levels are defined as method names, which accept two parameters: a string with a log $message
and an optional $context
array with additional data that does not fit well in the former string. Implementers may then replace placeholders in $message
with values from $context
.
A shared interface standard, like PSR-3, results in frameworks, libraries and other applications being able to type hint on that shared interface, allowing developers to choose a preferred implementation.
In other words: if a logging component is known to adhere to PSR-3, it can simply be swapped with a different PSR-3 compliant logging component. This assures maximum interoperability between calls to logger implementations.
Monolog recently implemented PSR-3. It’s therefore known to implement thePsrLogLoggerInterface
and its associated guidelines found in the PSR-3 document.
Criticism
The PHP-FIG is doing a great job of centralizing PHP standards.
Some people say that the PSRs go too far to define a global set of standards to define a coding style – something that is more subjective than objective. Others feel that a shared interface is too specific and not flexible. But criticism comes naturally with any standard initiative. People don’t like how identifiers are supposed to be named, which indentation is used, or how the standards are formed.
Most of the criticism and reflection takes place from the sideline, after the standards are accepted – even though the standards form in the mailing list (which is open for everyone to join in and leave feedback, comments or suggestions). Do not hesitate to open a new topic in the mailing list, if you think you have something valuable to add.
It’s also important to keep in mind that it’s not the specific combination of rules, which contribute to the benefit of the recommended standards, but rather having one consistent set of rules which are shared among various codebases.
By everyone shirking their own preferences, we have one consistent style from the outside-in, meaning I can use ANY package – not just whichever happens to be camelCase.
– Phil Sturgeon in the PHP-FIG mailing list
The Future
The FIG intends to host a cross-section of the PHP ecosystem, not only framework developers.
With a growing number of influential voting members and four accepted standards, the FIG is certainly gaining more traction in the PHP community. PSR-0 already has widespread usage, and hopefully PSR-1 and PSR-2 will follow suit to achieve more uniformity in shared PHP code.
With the shared interface defined in PSR-3, the Framework Interoperability Group took a new turn in recommending standards. They are still heading in that direction, as the contents of new shared interfaces are being discussed on the mailing list.
Currently there is an interesting discussion about the proposal of an HTTP Message Package, which holds shared interfaces for implementing an HTTP client. There are also various discussions proposing a shared Cache interface; but, as of now, it seems to be on low-activity.
No matter what the outcome of those proposals will be, the PHP-FIG is doing a great job of centralizing PHP standards. They are without a doubt influencing the PHP ecosphere in a positive manner, and hopefully their efforts will obtain a more prominent place in the PHP programming language.
Remember: currently, they still operate under the name of the Framework Interoperability Group, and have no intentions whatsoever to tell you – Joe the Programmer – how to build your applications. They merely recommend a set of standards that anyone can adopt.
Autoloading in PHP and the PSR-0 Standard
orginal source : http://www.sitepoint.com/autoloading-and-the-psr-0-standard/
Let’s say you have the file Rectangle.php which contains the definition for a Rectangle
class. Before you can create an instance of the object elsewhere in your code, you first need to pull in the Rectangle.php
file, perhaps by writing something like this:
<?php
require
"Rectangle.php"
;
$rect
=
new
Rectangle(42, 25);
Normally we put each class’ definition in its own file for better organization, and so you need to require/include each of the class files you want to use. If there are only a few files then it isn’t too much of a problem, but oftentimes that’s not the case. It can be very cumbersome to load a large library including all of its dependencies like this.
In this article I’ll walk you through the “history of autoloading,” from the older to the current PSR-0 standard autoloader approach found in many PHP frameworks such as Lithium, Symfony, Zend, etc. Then I will introduce you to the ClassLoader component from the Symfony2 project for PHP 5.3 which follows the PSR-0 standard.
Warning: Most of the code samples in the beginning of this article demonstrate deprecated approaches. It would be unwise to use them in production. I recommend you use one of the PSR-0 standard autoloaders instead.
Autoloading in the “Olden Days”
PHP 5 introduced the magic function __autoload()
which is automatically called when your code references a class or interface that hasn’t been loaded yet. This provides the runtime one last chance to load the definition before PHP fails with an error.
Here’s an example of an extremely basic __autoload()
implementation:
<?php
function
__autoload(
$className
) {
$filename
=
$className
.
".php"
;
if
(
is_readable
(
$filename
)) {
require
$filename
;
}
}
It’s a good idea to make sure a file exists before you try to include it, but sometimes the file may be there but will not have sufficient read permissions so it’s better to use is_readable()
over file_exists()
which will for test both conditions.
The major drawback to the __autoload()
function is that you can only provide one autoloader with it. PHP 5.1.2 introduced spl_autoload()
which allows you to register multiple autoloader functions, and in the future the__autoload()
function will be deprecated.
The introduction of spl_autoload_register()
gave programmers the ability to create an autoload chain, a series of functions that can be called to try and load a class or interface. For example:
<?php
function
autoloadModel(
$className
) {
$filename
=
"models/"
.
$className
.
".php"
;
if
(
is_readable
(
$filename
)) {
require
$filename
;
}
}
function
autoloadController(
$className
) {
$filename
=
"controllers/"
.
$className
.
".php"
;
if
(
is_readable
(
$filename
)) {
require
$filename
;
}
}
spl_autoload_register(
"autoloadModel"
);
spl_autoload_register(
"autoloadController"
);
Generally the functions are called in the order they’re registered, but the order can also be affected by additional arguments passed to spl_autoload_register()
.
It’s important to remember that once a function has been registered with spl_autoload_register()
, the__autoload()
function will no longer be called. If you have an __autoload()
function you want to run as part of your autoloader chain, then you’ll have to register it with spl_autoload_register()
.
Of course, the implementations of the autoloading functions I’ve shown this far have been rather simple. Real-world autoloaders are more complex.
Before real namespace support was introduced in PHP 5.3, developers devised their own approaches to prevent naming collisions. The PEAR Coding Standard used underscores to prefix class names with their directory path; the class Zend_Translate
for example would be defined in the file Zend/Translate.php
. The autoloader needed to replace the underscores with directory separators to locate the definition.
Also, different developers adopted different conventions when it came to naming their class files, for example the files might end in .php
, .class.php
, .inc
, etc. Some libraries may be installed in different paths as well. The loader needed to look in various places for them, so now the loader begins to look like this:
<?php
function
__autoload(
$className
) {
$extensions
=
array
(
".php"
,
".class.php"
,
".inc"
);
$paths
=
explode
(PATH_SEPARATOR, get_include_path());
$className
=
str_replace
(
"_"
, DIRECTORY_SEPARATOR,
$className
);
foreach
(
$paths
as
$path
) {
$filename
=
$path
. DIRECTORY_SEPARATOR .
$className
;
foreach
(
$extensions
as
$ext
) {
if
(
is_readable
(
$filename
.
$ext
)) {
require_once
$filename
.
$ext
;
break
;
}
}
}
}
Autoloading is a useful idea, but was an idea that desperately needed some standardization.
PSR-0 Standard
After PHP 5.3’s introduction of true namespace support, a group of people from the PHP community decided to create the PHP Standards Working Group in 2009 (later renamed to the Framework Interoperatability Group) and establish the PSR-0 standard which outlines various practices and constraints that must be followed for autoloader interoperability. Below are the requirements for PSR-0 compliance:
- A fully-qualified namespace and class must have the following structure
<Vendor Name>(<Namespace>)*<Class Name>
. - Each namespace must have a top-level namespace (“Vendor Name”).
- Each namespace can have as many sub-namespaces as it wishes.
- Each namespace separator is converted to a DIRECTORY_SEPARATOR when loading from the file system.
- Each underscore in the class name is converted to a
DIRECTORY_SEPARATOR
. The underscore has no special meaning in the namespace. - The fully-qualified namespace and class is suffixed with
.php
when loading from the file system. - Alphabetic characters in vendor names, namespaces, and class names may be of any combination of lower case and upper case.
According to the PSR-0 standard, there should be a top level directory with the vendor’s name and then the package name, so the directory tree will look like this:
The classes would then be namespaced accordingly:
<?php
namespace
VendorPackage;
class
Example
{
}
Thus, the class definition for DoctrineCommonConnections
would be found at/path/to/project/lib/Doctrine/Common/Connections.php
, and SymfonyCoreRequest
at/path/to/project/lib/Symfony/Core/Request.php
. The PSR-0 standard does not mandate what the base/path/to/project/lib
portion of the path is, and conforming autoloaders offer different methods for its resolution. Some will allow you to register the directory, some will search PHP’s include_path
, and some offer you both. Below is an example taken from the accepted PSR-0 standard.
<?php
function
autoload(
$className
)
{
$className
= ltrim(
$className
, '');
$fileName
=
''
;
$namespace
=
''
;
if
(
$lastNsPos
=
strripos
(
$className
, '')) {
$namespace
=
substr
(
$className
, 0,
$lastNsPos
);
$className
=
substr
(
$className
,
$lastNsPos
+ 1);
$fileName
=
str_replace
('', DIRECTORY_SEPARATOR,
$namespace
) . DIRECTORY_SEPARATOR;
}
$fileName
.=
str_replace
(
'_'
, DIRECTORY_SEPARATOR,
$className
) .
'.php'
;
require
$fileName
;
}
This gist by Jonathan Wage is a sample SplClassLoader
implementation that can load your classes if you follow the autoloader interoperability standards. It is the current recommended way to load PHP 5.3 classes that follow these standards.
You can use any one of the PSR-0 compliant autoloaders from frameworks such as Symfony, Pear2, AuraPHP (which is for PHP 5.4+), etc. and adhere to the rules above with your own code to take advantage of autoloading without the uncertainties I discussed previously.
Using Symfony’s Autoloader
The Symfony2 project is a component-based framework for PHP 5.3 and greater which you can use as a component library or as a full-stack framework. You can download Symfony’s Autoloader, the ClassLoader component, via different means — pear.symfony.com, packagist, or from GitHub.
Here’s the directory structure of Symfony’s ClassLoader component:
Using the component then looks like this:
<?php
require_once
"/path/to/Symfony/Component/ClassLoader/UniversalClassLoader.php"
;
use
SymfonyComponentClassLoaderUniversalClassLoader;
$loader
=
new
UniversalClassLoader();
$loader
->registerNamespace(
"SymfonyComponent"
=>
"/path/to/symfony/components"
);
$loader
->registerNamespace(
"Monolog"
=>
"path/to/monolog/src/"
);
$loader
->registerPrefix(
"Zend_"
,
"path/to/zend/library"
);
$loader
->register();
The registerNamespace()
method is used to inform the autoloader where the given namespace’s base directory maps to on the file system and accepts a namespace as its first argument and path as its second value. You can also register multiple namespaces in a single call with the registerNamespaces()
method.
<?php
$loader
->registerNamespaces(
array
(
"SymfonyComponent"
=>
"/path/to/symfony/components"
,
"Monolog' => "
path/to/monolog/src"));
The registerPrefix()
method is used to register pseudo-namespaces which was used by Pear, Zend, and other libraries and frameworks before real namespace support was implemented in PHP as we have already covered above. You can also register mulitple ones with the registerPrefixes()
method and passing it as an associative array.
<?php
$loader
->registerPrefixes(
array
(
"Zend_"
=>
"/path/to/zend/library"
,
"Twig_"
=>
"path/to/twig/library"
));
If you are using the Alternative PHP Cache (APC), a free and open source opcode cache for PHP, then you can may want to consider using the ApcUniversalClassLoader
class. The ApcUniversalClassLoader
extends theUniversalClassLoader
but uses apc_store()
and apc_fetch()
to store lookup information in APC’s cache. The standard UniversalClassLoader
will of course work with APC, but the additional behavior offered by the ApcUniversalClassLoader
class afford extra performance benefit.
<?php
require_once
"path/to/Symfony/Component/ClassLoader/UniversalClassLoader.php"
;
require_once
"path/to/Symfony/Component/ClassLoader/ApcUniversalClassLoader.php"
;
use
SymfonyComponentClassLoaderApcUniversalClassLoader;
$loader
=
new
ApcUniversalClassLoader(
"apc.prefix."
);
The ApcUniversalClassLoader
accepts a prefix with its constructor. For more information on APC, I suggest reading the APC documentation.
Summary
In this article we have discussed autoloading, from its early days to the current PSR-0 standard which has become widely adopted across many PHP frameworks. Recently, David Coallier tried to push the SplClassloader
class into PHP 5.4 to offer native PSR-0 compliant autoloading functionality, but for various reasons it didn’t happen. Maybe in the future we will see it added. (See the C extension at gist.github.com/1310352.)
Now the current hot discussion in the working group is focused on caching. If it’s something you’d like to be part of, feel free to join the discussion!
centos: Another MySQL daemon already running with the same unix socket
original source : http://stackoverflow.com/questions/20407292/centos-another-mysql-daemon-already-running-with-the-same-unix-socket
To prevent the problem from occurring, you must perform a graceful shutdown of the server from the command line rather than powering off the server.
# shutdown -h now
This will stop the running services before powering down the machine.
Based on Centos, an additional method for getting it back up again when you run into this problem is to move mysql.sock:
# mv /var/lib/mysql/mysql.sock /var/lib/mysql/mysql.sock.bak
# service mysqld start
Restarting the service creates a new entry called mqsql.sock
Laravel : Query Scopes, Accessors and Mutators
original source : http://www.ashwinsureshkumar.com/laravel-query-scopes-accessors-and-mutators/
This post is about few simple concepts but very powerfull when used.
Query Scopes
Query scopes are easier way to re-use logic in your model than writing where clauses all over again and again for the same logic.
We will use a user model which has a property “active” a boolean value.
User
-id [1]
-username [john]
-firstname [john]
-lastname [doe]
-password [hashedpassword]
-active [1]
We need to query for all users who are active (active = 1). To use scopes we prefix the function name with “scope”. Below is example for querying for active users.
class User extends Eloquent {
public function scopeActive($query){
return $query->where('active' , '=', 1);
}
}
You can retrieve the active users as below. Also, you can use multiple scopes on a model.
$users = User::active()->get();
/*multiple scopes - active users - male users
assuming that scopeMale function is added to the model */
$male_users = User::active()->male()->get();
Mutators
Mutuators can be utitlised to manipulate the data before saving into the database. One of the place where I use mutators are for passwords. Lets consider the same user model, when creating/updating or seeding a user you have to hash the password. So you would do something like $user->password = Hash::make('password');
Since password has to be hashed everytime before saving into the database it would be nice if we could do it one place and just before saving. We can achieve this using mutators.
class User extends Eloquent {
public function setPasswordAttribute($value) {
$this->attributes['password'] = Hash::make($value);
}
}
Accessors
Accessors are opposite to mutators, it lets us to manipuldate the data just before returning the data on query. For example, we want to capitalize the first letter in the first name everytime. I am just going to write the function since it is understood that it is inside the user model.
public function getFirstNameAttribute($value){
return ucfirst($value);
}
We can also use this to get custom property on the model. For example, a property on the user model “full_name” which would concatenate first name and last name. Notice that this would return first name with first letter capitalized since we did that in the previous accessor method.
public function getFullNameAttribute($value){
return $this->first_name . " " . $this->last_name;
}
$user = User::find(1);
$user->full_name;
//John doe
Laravel 4 Eloquent Model Relationships, Part 1. – Code Planet
The Benefits of Making Your Models “Eloquent”
If you are familiar with MVC and are learning Laravel 4, you may be tempted to simply use models as a place to store your database logic. However, you would be robbing yourself of the many benefits of extending the Eloquent Object-Relational Mapper in your applications.
Among these benefits are route & form model binding – both of which are features that can save you loads of time and spare you from having to write the same boring code that is required in just about every web application.
Enter Laravel Model Relationships
One of the more powerful features of the Eloquent ORM are model relationships. Model relationships, once defined, enable you to fetch & update a model object in your database, as well as any models it is related to, without having to write explicit query logic. Common tasks like fetching blog posts along with all metadata, author data, and comments associated with them become trivial.
As of Laravel 4.0 there were the 3 primary types of relationships:
- One-to-One
- One-to-Many
- Many-to-Many
Laravel 4.1 (released late 2013) brings with it a couple more relationship types:
- Has-Many-Through
- Polymorphic One-to-One/One-to-Many
This article will cover the first 3 relationship types available as of Laravel 4.0; one-to-one, one-to-many, & many-to-many.
Look for a future article that will cover Eloquent relationships introduced in Laravel 4.1.
A Simple Blog Example
For the sake of illustration, we will be looking at how these relationships might be used in a real-world web application, such as a blog.
This demo project is a very simple web development blog that has posts, authors, & content tags (i.e. HTML, CSS, Javascript, PHP, MySQL, MongoDB).
The project that we will be using can be found here: https://github.com/dtrenz/laravel-model-demo
To setup the project;
- clone the repo
- run
composer install
- create a new database in MySQL
- update the db connecton (i.e. host, database, username, password) in app/config/database.php
- run migrations, to setup the DB schema:
php artisan migrate
- seed the DB with sample data:
php artisan db:seed
One-to-One
Let’s start with a one-to-one relationship. For the purposes of this demo, I’ve chosen a somewhat contrived example of a one-to-one relationship.
Each blog post has a title and body text, but the body text is stored in a separate table, called “texts.”
Here is the schema for posts and texts:
posts- id- titletexts- id- text- post_id
You can see that the texts table has a foreign key of post_id, since each post “owns” one text.
Eloquent needs to know how to map a relationship from a post to text. We define this relationship in each model.
First, we create a model file for each of these models, tell Eloquent which table to find the data for the model, and then define the relationship using a model method:
That was easy, right?
All we had to do was return a hasOne relationship to the Text model and now, anytime you need to access or display the text for a given post, you can simply reference the text attached to the post as if it were a direct property on the post object:
$post->text
But…how?
By returning a hasOne relationship in a method called “text()” Eloquent is able to map that method to the row in the texts table with the current post_id. It then returns that row as an instance of the Text model. This enables you to get the text, like so:
$post->text()->first()
But that’s not all! Eloquent gives you a dynamic property for accessing the text directly, w/o having to use query builder methods like “first().” This enables you to get the text, like so:
$post->text
One-to-Many
Next, let’s try a one-to-many relationship – this is probably the most common relationship type you will use. In our blog we have posts and each post belongs to a single author. In other words, one author can have many posts.
Let’s take a look at the relevant part of the schema:
users- id- nameposts- id- title- author_id (aliased user.id)
There are 2 things you should notice here; (1) we have a users table to store all kinds of users on our website (i.e. authors, commenters, admins), and (2) we have added a new column – author_id – to the posts table, which is the foreign key to the users table.
Now, I could have simply named it user_id, but I felt that was too vague. What kind of post user is this? Is this the author of the post, or a commenter, etc? By naming the column author_id, it makes the relationship much clearer and, fortunately, Eloquent makes this very easy to manage.
Next, let’s create a User model and define a one-to-many relationship to the Post model:
To define a one-to-many relationship, we simply return a hasMany relationship to the Post model and – since we are aliasing the foreign key – we pass the name of the foreign key column we want to use as the second parameter. If you simply wanted to use user_id as the column name, you would not need to pass a second argument.
Now we can access all posts by an author like so:
$author->posts
Since this is a one-to-many relationship, instead of getting back a single Post instance, we get a collection of multiple Post instances. Then, to access/display each instance, we could simply loop through them:
Pretty great, right?
So, now we can get posts for a given author, but when we display a single post page, we also want to be able to display author attribution. So, how do we get the relationship to go the other way, to get the author for a given post?
The answer is simple: For every model relationship you define, there is a way to define the inverse relation. For any one-to-* relationship, you can use the belongsTo method to create an inverse mapping.
So, let’s add an “author()” method to the Post model that returns a belongsTo relationship.
Now, we can display the author’s name on a post page like so:
Many-to-Many
The last relationship type we will be covering is many-to-many. In the blog we have content tags for tagging posts based on what topics are discussed (i.e. HTML, PHP, MySQL).
A post can have many tags, and a tag may be attributed to many posts, thus we have a many-to-many relationship between posts and tags.
Let’s take a look at the schema for tags:
tags- id- namepost_tag (pivot table)- post_id- tag_id- author_id (aliased user.id)
Just as you would expect, we add a table called tags w/ an auto-incrementing “id” column. But we are establishing a many-to-many relationship, so we cannot simply add a foreign key to either table, since that would limit us to a single owner.
This is why we also need to add a pivot table that maps post_ids to tag_ids. Fortunately, Eloquent expects this in a many-to-many relationship and knows to look for a table named in this format (“model_model”) in order to map properly to the other model.
To define the relationship, just like the previous examples, we simply add a mapping method to each model:
That’s all! Here we simply use the belongsToMany relationship method on both sides of the relationship to be able to map between the models:
It should be noted that – while this pivot table naming convention is the recommended and default convention for an Eloquent many-to-many pivot table – you are welcome to name the pivotal table whatever you like (just like we did with author_id) by passing the name as the second argument of the belongsToMany method.
Working with Laravel Model Relationships
Now that we have defined all of these relationships between our models, what else can we do with them?
We’ve seen how we can access and read the data through these model relationships, but what happens if we want to write data?
Let’s say we are creating a new blog post, what will that entail?
First, We’ll need to create a new Post & a new Text that will be attached to that Post.
This can be accomplished very easily by using the query builder save() method:
Second, we’ll need to associate an existing User to the Post as the author & associate some existing tag(s) to the post:
Pretty cool, right?
I don’t know about you, but when I think of all of the query logic I didn’t have to write to make all of this happen, I get pretty excited.
The End…?
This article introduces the fundamentals of Eloquent ORM model relationships in Laravel, but there are many more aspects that you should look into, such as eager loading.
As I mentioned at the top, more relationships were added in Laravel 4.1 (i.e. Polymorphic Relations & Has-Many-Through), so expect a follow-up to this article that will cover those.
어떤 방식의 전화를 실행할것인가 하는 내용이 담긴 화일을 /var/spool/asterisk/outgoing 폴더안에 넣으면 자동으로 전화가 걸리게 된다.
음성화일은 /var/lib/asterisk/sounds/en 안에 넣는다.
예시)
화일명: hello-world.call
화일내용:
Channel:motif/g18thcenturyprogrammergmailcom/1503*******@voice.google.com
Application:Playback
Data:hello-world
——- 설명 1503******* 는 목표에 해당하는 전화번호.Data: 에는 음성화일이름을 넣는다.