【PHP】七牛云存储 SDK of PHP 基础使用

为了七牛大赛!!!

研究了一天的七牛云存储 PHP SDK,他的上面文档说的都是代码片段,不能拿来直接用,我现在把基本操作已经封装好,直接引入文件就好。下面来看看基本的实现。

首先要去官网下载好PHP的sdk,http://developer.qiniu.com/download/index.html ,解压以后把qiniu这个文件夹放在自己的php工作项目目录下。这一步是以后所有的前提。

官方文档在这里:http://developer.qiniu.com/docs/v6/sdk/php-sdk.html

我自己封装的代码:
第一行要引入这个文件

require_once("qiniu/rs.php");

这两个参数是七牛给你的,注册账号以后会有

	private $accessKey =【自己填】 ;
	private $secretKey =【自己填】 ;
	private $client;

初始化函数,每一个方法都需要调用这个

	/**
	 * 初始化
	 */
	private function Init(){
		$this->accessKey = '';
		$this->secretKey = '';
		Qiniu_SetKeys($this->accessKey, $this->secretKey);
		$this->client = new Qiniu_MacHttpClient(null);
	}

下面的方法可以查看单个文件信息

	/**
	 * 查看单个文件信息
	 * @param string $bucket 空间名称
	 * @param string $key    文件名
	 */
	function FileInfo($bucket,$key){
		$this->Init();
		list($ret,$err) = Qiniu_RS_Stat($this->client, $bucket, $key);
		echo $key." info is \n";
		if($err!==null){
			var_dump($err);
		}else{
			var_dump($ret);
		}
	}
	

复制一个文件

	/**
	 * 复制文件
	 * @param string $bucketSrc  源空间
	 * @param string  $keySrc    源文件名
	 * @param string $bucketDest 目标空间
	 * @param string $keyDest    目标空间名
	 */
	function CopyFile($bucketSrc,$keySrc,$bucketDest,$keyDest){
		$this->Init();
		$err = 	Qiniu_RS_Copy($this->client, $bucketSrc, $keySrc, $bucketDest, $keyDest);
		echo $keySrc." copy result:\n";
		if($err!==null){
			var_dump($err);
		}else{
			echo "seccuss!\n".$keyDest." is at ".$bucketDest;
		}
	}

移动一个文件

	/**
	 * 移动文件
	 * @param string $bucketSrc     源空间
	 * @param string $keySrc        源文件名
	 * @param string $bucketDest    目标空间
	 * @param string $keyDest       目标文件名
	 */
	function MoveFile($bucketSrc,$keySrc,$bucketDest,$keyDest){
		$this->Init();
		$err = 	Qiniu_RS_Move($this->client, $bucketSrc, $keySrc, $bucketDest, $keyDest);
		echo $keySrc." move result:\n";
		if($err!==null){
			var_dump($err);
		}else{
			echo "seccuss!\n".$keyDest." is at ".$bucketDest;
		}
	}

删除一个文件

	/**
	 * 删除文件
	 * @param string $bucket  空间
	 * @param string $key     文件名
	 */
	function DeleteFile($bucket,$key){
		$this->Init();
		$err = Qiniu_RS_Delete($this->client,$bucket,$key);
		echo $key." delete result:\n";
		if($err!==null){
			var_dump($err);
		}else{
			echo "seccuss!\n";
		}
	}

获取token,这个很重要,必须要注意。客户端必须要有token才可以上传或者下载

	/**
	 * 获取上传Token
	 * @param unknown $bucket 上传目的空间
	 * @return string uptoken 上传token
	 */
	 function CreateUploadToken($bucket)  {
		$this->Init();
		$putPolicy = new Qiniu_RS_PutPolicy($bucket);
		//设置返回URL
 		$putPolicy->ReturnUrl = "http://localhost/workspace/qiniuProject/OK.html";
		$upToken = $putPolicy->Token(null);
		return $upToken;
	}

上传文件

	/**
	 * 上传文件
	 * @param string $bucket    上传空间
	 * @param string $key       上传以后的文件名
	 * @param string $fileName  要上传的文件名
	 */
	function UploadFile($bucket,$key,$fileName){
		require_once("qiniu/io.php");
		$this->Init();
		$upToken=$this->CreateUploadToken($bucket);
		$putExtra = new Qiniu_PutExtra();
		$putExtra->Crc32=1;
		list($ret,$err) = Qiniu_PutFile($upToken, $key, $fileName, $putExtra);
		echo $key." upload result \n";
		if($err!==null){
			var_dump($err);
		}else{
			var_dump($ret);
			echo $key." is at ".$bucket;
		}
	}

如果是图片,可以用这个查看图片信息

	/**
	 * 查看图片信息
	 * @param string $domain  域名
	 * @param string $key     文件名
	 */
	function ImageInfo($domain,$key){
		require_once("qiniu/fop.php");
		$this->Init();
		//生成baseURL
		$baseURL = Qiniu_RS_MakeBaseUrl($domain, $key);
		//生成fopURL
		$imageInfo = new Qiniu_ImageInfo();
		$imageInfoURL = $imageInfo->MakeRequest($baseURL);
		echo "the info of ".$key." is at <a href="$imageInfoURL" target="__blank">".$imageInfoURL."</a>
";
	}

如果是数码相机拍摄的,可以看EXIF信息

	/**
	 * 查看图片的Exif信息
	 * @param string  $domain  域名
	 * @param string  $key  文件名
	 */
	function ImageExifInfo($domain,$key){
		require_once("qiniu/fop.php");
		$this->Init();
		//生成baseURL
		$baseURL = Qiniu_RS_MakeBaseUrl($domain, $key);
		//生成fopURL
		$imageExifInfo = new Qiniu_Exif;
		$imageExifInfoURL = $imageExifInfo->MakeRequest($baseURL);
 		echo "the Exifinfo of ".$key." is at <a href="$imageExifInfoURL" target="__blank">".$imageExifInfoURL."</a>
";
;
	}

查看文件,缩略图,可以指定高度宽度

	/**
	 *查看文件
	 * @param string $domain  域名
	 * @param string $key     文件名
	 * @param string $width   宽度
	 * @param string $height  高度
	 */
	function ImageView($domain,$key,$width,$height){
		require_once("qiniu/fop.php");
		$this->Init();
		//生成baseURL
		$baseURL = Qiniu_RS_MakeBaseUrl($domain, $key);
		//生成fopURL
		$imageView = new Qiniu_ImageView();
		$imageView->Mode = 1;
		$imageView->Height = $height;
        $imageView->Width = $width;
        $imageViewUrl = $imageView->MakeRequest($baseURL);
        echo "the view of ".$key." is at <a href="$imageViewUrl" target="__blank">".$imageViewUrl."</a>
";
	}

可以为资源生成一个二维码

	/**
	 * 生成二维码
	 * @param string $domain    域名
	 * @param string $key       文件名
	 */
	function CreateQrcode($domain,$key){
		require_once("qiniu/fop.php");
		$this->Init();
		//生成baseURL
		$baseURL = Qiniu_RS_MakeBaseUrl($domain, $key);
		$qrcodeURL  = $baseURL."?qrcode/0/level/L";
		echo "the Qrcode of ".$key." is at <a href="$qrcodeURL" target="__blank">".$qrcodeURL."</a>
";

	}

这就是几乎全部的PHP操纵七牛API了。要注意的是一定要有AK和SK,七牛会给你一个,并且一定要保留好你的SK。
完整的文件在这里下载:http://liukaining.qiniudn.com/QNProcess.class.php
调用的时候把这个文件引入,并且把这个文件放在和qiniu文件夹同级。

就是这样了,我后面会继续总结高级用法,欢迎关注!

为了大赛加油!

刘凯宁@C2P
20140818

Share

【PHP】Becoming a PHP Professional[3]Social aspects of teamwork

这几天工作压力不是很大,今天继续把第三篇文章放上来哈 

After discussing the general guidelines to reaching an Intermediate+ level in PHP development in Part 1 and the importance of others around you in Part 2, this article will focus on social aspects of teamwork and initiative, and will serve as an introduction into a more concrete and practical teamwork based article coming soon.

It’s important to note that when I say teamwork, I don’t only mean teams while working for a larger entity – a corporation or company in which you’re a minor sub-group. A team is also a group of freelancers working together on a project – either close by, or remotely. Whenever you work with someone in any capacity whatsoever – that’s a team. A loose team, but a team nonetheless.

Know your role

It’s no secret we developers tend to be bigheaded sometimes – in all areas of life, not just coding – especially when being given (or succeeding in) a task of mid to high level importance. It gives us a sense of false security and we tend to forget that we don’t, in fact, know everything

t’s only natural, then, that we feel like we’re more important than our designated team role lets on. In times like these, it’s important to step back, cool down, and look at things from a different perspective. Put yourself into the shoes of other team members and look at yourself from afar. Realize why you’re there and what you’re supposed to do, and respect the fact that every member of the team has a specific purpose.

You might be better at front end engineering than the team member they hired for the position, but if you’re there doing PHP, consider the net gain of proclaiming such a fact publicly. While the front end dev might be mediocre, you were mediocre at one point too – without the experience of working on different projects, you never would have outgrown the mediocrity. Furthermore, what can be gained by replacing said member? If the member is actually bad at his job and does harm to the project, by all means, this should be brought to the team lead’s attention. But if he’s just “ok”, replacing him could actually have a negative impact on the progress of the work, causing unnecessary delays.

Not stating the fact publicly could have even worse implications – it could sow dissent in the ranks, making the other team members take either a defensive stance against you due to your underhandedness, or taking an aggressive stance towards the person you have a problem with which, again, isn’t healthy for the team as a whole. The healthiest solution is, by far, approaching the person in a friendly manner, giving advice, and discussing everything openly.

But what if it’s the project lead who is so bad he does harm to the project? Well…Respect superiors – to a degree

Superiors are like elders – they’re to be respected, but to a certain degree. Of course I’ll listen to what my grandma has to say. She’s been around for much longer, she’s bound to have at least passively absorbed some wisdom she can impart. But if she starts trying to brainwash me with old habits and attitudes, her close-mindedness will render me non receptive to her words.

It’s the same with superiors in a team. Respect their decisions, accept their advice. If someone is higher up on the corporate or team ladder than you are, there’s a reason for that – and more often than not it actually is skill and experience, contrary to many people’s beliefs. Keep in mind that everyone you ever meet knows something you don’t, and be receptive of their opinions, even if you disagree with them – there’s often more to be learned from disagreement than agreement. A light difference in opinion can be researched and discussed productively, and someone is guaranteed to come out of the situation with knowledge they didn’t have before.

Admittedly, there’s a dark side, too. There are times when the only reason someone is superior to you is because they’re better connected to the project owner. These circumstances usually aren’t obvious at first, but in time, they always become fully transparent. Speaking from experience, the symptoms of incompetence can be anything from refusing to move away from PHP 5.2 in 2012 on a brand new project, to contradicting oneself in tasks just to cover up for previous errors in judgement. It won’t be long before their bad calls start to harm the project – soon enough, everything that goes well will mysteriously be attributed to them, and everything that goes wrong will require an in-team scapegoat. This type of person is usually excellent at diverting attention and misdirection in order to keep their position as long as possible, because their high rank usually involves bonuses or other privileges – and if the project falls through eventually, it’s just one black spot on their CV, but a thick bank account and lots of influence.

When you detect such an environment, there’s no rational way to repair it. Going to the project owner usually makes no sense, because they’re either too attached to the person (blood relatives, personal friends) or completely fooled – and the latter is usually worse, because the longer the situation lasts, the less willing the CEO or project owner becomes to admit that they’ve been duped all that time. Projects like that usually crash and burn after a prolonged state of plateau, so…

Don’t be afraid to leave

When you realize this might be the case, it’s important not to be afraid to leave. The temporary security the job offers at that stage is just that – temporary. Remember, the project will crash and burn, undoubtedly, it’s just a matter of time. The situation is unfixable without a change in management, and changes in management don’t tend to happen all that often.

You should always be on the lookout for better offers, but when you find yourself in a downhill situation, start actively looking. Go to interviews, apply for projects, just don’t be passive about it. It’s hard when you have dependents, and risking the loss of a regular paycheck can be very taxing on one’s psyche, but trust me when I say that sticking around in such an environment can be even more taxing, not only for you, but those around you as well.

 

I write from personal experience. I was forced to leave my job due to these exact conditions, but instead of settling for a similar pay with another IT company, I opted to go freelance. Going freelance allowed me to pick my own projects and clients, to choose technologies I’m comfortable with or interested in, and to learn more than I would ever have learned having remained stuck in the faulty team.

Conclusion

While this article had little to do directly with PHP, it is the opinion and experience of someone specialized in PHP. It’s also a precursor to the next article on teamwork which will cover remote work, pair programming, dealing with time zone differences, types of teamwork, and more.

What I’d like you to take away from this part is – don’t be a slave of circumstance. Be courteous, professional and honest, but don’t be afraid to leave a poisonous environment – it harms you, the people who love and support you, and finally, the project you’re working on. I left and, personally, I have yet to look back with anything but relief.

Do you have any team based horror stories? Success stories perhaps? Attitudes differing from those exposed in this article? Let me know in the comments below

 刘凯宁@C2P
20140722

 

Share

Becoming a PHP Professional【part 1】The Missing Link

这是我上次给大家介绍的那篇文章,今天放在这里,希望大家都能尽快变得Professional 

Becoming a PHP Professional:

The Missing Link

When reading various PHP related blogs, Quora questions, Google+ communities, newsletters and magazines, I often notice extreme polarization of skill. Questions are either at the “How do I connect to a MySQL database?” level or something in the range of “How do I best scale my mailing system to send over one million emails per hour without introducing a new server?”

I personally distinguish between 4 distinct levels of PHP prowess (likely applicable to any language/profession):beginner,intermediate, professional and elite.

The extremes

In PHP, beginners learn about variables, includes, form processing. They learn simple logic constructs. They send an email with the help of a tutorial, maybe even touch on an object oriented programming example without actually understanding it. They work with Word Press and modify a couple CSS classes. With this knowledge, they apply for jobs and, unfortunately, usually fail.

Professionals are those who have given good parts of their lives to many projects. They’ve deployed commercial applications in most if not all frameworks, they’ve used different databases with PHP efficiently, they visited and/or talked at conferences. They studied design patterns and can easily engineer an entire project on their own from diagrams to execution. They left procedural code far behind.

Elite programmers are professionals who put in the fabled 10000+ hours into honing their skill. They supplement their PHP installations with extensions they wrote themselves, they find bugs just by glancing through source files, they are extremely meticulous about their code layout. They reject all but the most complex projects and find alternative and imaginative ways to solve problems people didn’t even know they had. They’ve written some well received books about the language, spoke at dozens of conferences, maybe even made their own branch of PHP or a highly successful framework or two.

So in all this, who are the intermediate ones?

The missing link

How does one get from beginner to pro and beyond? If one doesn’t know anything beyond the basics, how can they improve their skill enough to leave the bad practices behind and start practicing the more advanced approaches? This is a question I get asked a lot by beginners. In order to become a professional, one must first become intermediate.

What follows is a list of what one should go through on the path to PHP fluency.

Abandon spaghetti code

Many people think using classes means you’re writing object oriented code, while using functions means you’re writing procedural code. While this is false, for the sake of this argument, let’s assume the widespread vanilla definition: procedural code is code in which you simply don’t use classes and objects, and OOP code is code in which you use classes and objects as much as possible.

My advice is to fully abandon procedural code. Use object oriented coding style as much as possible – write classes, encapsulate logic, think with real world terminology. The performance benefit of procedural code over class based code is negligible when compared to the re-usability that proper OOP code gives you and future developers inheriting your project. A common argument against this is “But, Word Press is procedural!” To be frank, and this might sound harsh, “Word Press developers” are no more PHP developers than people with Instagram are photographers. Please don’t take this to mean WP is useless – it’s fantastic for blogs, simple websites and one-day projects you don’t want to spend too much time on. It’s excellent for making a quick buck or for people who aren’t too technical, but mastering WP will never make you a professional PHP developer – it’s a yarn of spaghetti code that can teach you no proper design principles.

Start small. Think of a real world concept, and try to represent it in OOP code. Work through some basic tutorialsand slowly go more advanced. Work on OOP code until you understand classes in general before transitioning to proper frameworks and confusing terms like “Model”, “View” and “Controller” – all these are foggy, abstract terms without having a solid foundation in OOP first.

Dissect existing projects

Dive into existing source code wherever you can find it. For example, look up PHP projects on Github, clone them, deploy them locally on your own machine and try to play around with the code. Go file by file, line by line, until you understand what each does.

Look for projects that are well commented and/or documented, well structured, and still alive. Projects last updated in 2008 won’t do you much good if you’re getting into PHP 5.5 – you’ll likely be missing out on the latest and greatest features that could make you stand out in an already overpopulated field.

Learn to set up your own PHP environment

Being able to set up your own environment is a priceless skill. Not only does it allow you to fine tune your setup, it also familiarizes you with building extensions from source.

Abandon Windows for development – if your main desktop is Windows, install virtualization software and run a Linux virtual machine – the case insensitivity of Windows, its line endings, and all other oddities inconsistent with most server environments out there are just asking for trouble, so it’s best to develop on a system that most resembles the environment you’ll eventually be launching on.

Virtual machines also help you experiment – if something goes wrong, you can just wipe it and start over or do a rollback. You can literally experiment as much as you want without fear of messing anything up. Mastering tools is important, but having a good workbench is too.

Experimenting with your own setups will also allow you to get familiar with the different servers out there – whether to use Apache of Nginx, whether to use neither of them and go with Appserver, and so on.

Exercise best practices early

When writing your own code, make sure you comment heavily with docblocks, indent beautifully and structure carefully. After you build a class, project or library, use well known documentation tools (PHPDocumentor,ApiGen) to extract the docblocks and improve on them.

A good IDE is worth its disk size in gold – getting used to one multi platform editor can help you be up and running in no time when setting up a fresh environment, so you can dive into code instantly without wasting time on setting up keyboard shortcuts and themes. Make sure you back up IDE configuration files on a cloud service like Google Drive, so you have them ready for import at all times even if you need to make a fresh installation. A good IDE isPHPStorm, or if you can’t afford it or have no open source projects with which to ask for a free license, Netbeansis a free alternative. Both are multi-platform.

Getting used to best practices early helps you remain consistent and lets other people read your code much more fluently. Find your style and stick to it – you’ll help both yourself and others. Try to follow the PSR standards (PSR-0, PSR-1, PSR-2, PSR-3) as closely as possible – they’re called standards for a reason. Most of us use and love them, and they make everyone’s code equally reusable and readable.

A good beginner friendly resource that gives up-to-date hints is PHP the right way – use it to get familiar with the latest best practices, basics of OOP, security, deployment, coding standards I mentioned above, and much more.

Try out different frameworks, choose one

For a long time, PHP was the language with most frameworks out there (JavaScript took over recently). Whether this speaks of the inconsistency of our community or the popularity of our language, I cannot say, but the fact remains that choosing a framework is a daunting task, especially when first starting out.

Having tried most of them, I can wholeheartedly recommend Phalcon as the go-to framework due to its robustness and quality, and the fact that it’s built in C and installed as a PHP extension (thus being faster than any current framework in existence). However, trying out different frameworks is an absolute necessity.

When you try them out, you learn about a new approach to a common problem every time. Each framework has its own quirks you’ll like and downsides you’ll hate but most importantly, you’ll learn about the mindset of others (particularly the developers of the framework). You’ll see new usages and approaches, and a very good exercise is re-building one of your sample projects in as many frameworks as you can find. This will help you efficiently gauge the efficacy of a particular framework: the speed of developing in it and its performance.

Read

Don’t underestimate the hints and tips of others. Read as much as you can – if you keep at it, it doesn’t take as much time as you might think. Find good blogs to follow, read the tutorials on this website, traverse questions and answers on StackOverflow, visit the SitePoint Forums, subscribe to newsletters, follow good sources on Google+. Avoid basic PHP tutorial books – they’re outdated as soon as they’re published – instead, focus on individual snippets and tutorials of useful up-to-date code you can find all over the web. Even if the topic is something you’ve already covered, try giving it a read – you’ll often find that something new can be learned by reading someone else’s perspective on the very same thing.

If there’s no work, invent some

There is always something to do. Never catch yourself saying “I don’t have a project” or even worse, “I’m bored”. If you don’t have an active project to work on – make one up. Do you use a tool daily that frustrates you with its lack of functionality? Build a better alternative! Have no ideas for new products? Replicate existing ones – tryrebuilding a basic Facebook, recreate something you already know exists just for practice.

What’s most important is to never stop – there’s no amassing 10000 hours if you don’t put in the hours! Keep working, keep yourself interested and engaged. Make a simple address book app. Then rebuild it in another framework. Then rebuild it with another database (replace MariaDB with Mongo, for example). Keep busy!

Find a buddy/mentor

It’s easier to learn when you have someone to do it with. Find a buddy who shares your passion. Maybe you’re one of the lucky few with a partner who shares your geeky interests. Maybe you’re in school or university and have peers who would like to get started as well and need companionship in these adventures. You can even find a mentor and receive expert guidance.

Never underestimate the power of a companion – there’s a reason The Doctor always has one!

Conclusion

When you focus on all these entries with as much will as you can muster, when you realize it’s what you want and keep at it – you’re on the road to becoming a PHP pro. Maintain discipline, never give up (even if others around you do) and keep practicing.

If you’ve got any useful resources you’d like to share with us on how you bridged (or are currently bridging) the Intermediate gap, let us know in the comments below!

*************************************************************************************************原文有4篇,分四次发布。
2014年6月30日

Share